抽象类和唯一指针 [英] Abstract class and unique pointer
本文介绍了抽象类和唯一指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码中出现以下错误:
I have the following error in my code:
错误:分配抽象类类型为材料"的对象
我不知道该如何处理.
我知道 std :: make_unique
执行分配,因此它无法分配 Material
类型的对象,但是我不知道如何纠正它.
I'm aware that std::make_unique
performs an allocation, so it can't allocate the object of type Material
, but I don't know how to correct it.
#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()
:
tries to create an instance of class Material
, it is irrelevant what type mat1
has. You seem to need method clone()
in your class:
class Material {
...
virtual std::unique_ptr<Material> clone() const = 0;
};
然后 Mix
ctor将是:
Mix(const Material& mat1, const Material& mat2)
: mat1_(mat1.clone())
, mat2_(mat2.clone())
{}
,您需要在每个派生类中实现 clone()
:
and you need to implement clone()
in every derived class:
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;
}
};
这篇关于抽象类和唯一指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文