小编V.C*_*tte的帖子

抽象类和唯一指针

我的代码中出现以下错误:

error: allocating an object of abstract class type 'Material'

我不知道如何处理这个案子.

我知道std::make_unique执行分配,所以它不能分配类型的对象Material,但我不知道如何纠正它.

#include <iostream>
#include <memory>

struct Material
{
  Material() = default;
  virtual int get_color() const = 0;
};

struct Basic : public Material
{
  Basic() = default;
  virtual int get_color() const override
  {
    return 1;
  }
};

struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_(std::make_unique<Material>(mat1))
    , mat2_(std::make_unique<Material>(mat2))
  {}

  virtual int get_color() const override
  {
    return mat1_->get_color() + mat2_->get_color();
  } …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance constructor abstract-class c++14

9
推荐指数
1
解决办法
4200
查看次数

标签 统计

abstract-class ×1

c++ ×1

c++14 ×1

constructor ×1

inheritance ×1