我的代码中有以下错误:
错误:分配抽象类类型“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();
}
private:
std::unique_ptr<Material> mat1_;
std::unique_ptr<Material> mat2_;
};
int main()
{
auto mix = Mix(Basic(), Basic());
std::cout << mix.get_color() << '\n';
}
最佳答案
这个调用:
std::make_unique<Material>(mat1)
尝试创建类 Material
的实例,与 mat1
的类型无关。您似乎需要在您的类中使用方法 clone()
:
class Material {
...
virtual std::unique_ptr<Material> clone() const = 0;
};
那么 Mix
构造器将是:
Mix(const Material& mat1, const Material& mat2)
: mat1_(mat1.clone())
, mat2_(mat2.clone())
{}
并且您需要在每个派生类中实现clone()
:
struct Basic : public Material
{
Basic() = default;
virtual std::unique_ptr<Material> clone() const override
{
return std::make_unique<Basic>( *this );
}
virtual int get_color() const override
{
return 1;
}
};
关于c++ - 抽象类和唯一指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44413478/