将派生类对象加入基类unique_ptr类型vector时触发E0304错误如何解决
错误原因
- 继承方式不符合要求:C++中
class声明的继承默认是私有继承,你写的class Sheep : Organism等价于class Sheep : private Organism,私有继承场景下派生类指针无法隐式转换为基类指针,因此std::unique_ptr<Sheep>无法自动转为std::unique_ptr<Organism>匹配push_back的参数要求。 - 构造函数权限不足:
Sheep类的构造函数默认是private权限,std::make_unique无法访问私有构造函数,无法成功创建Sheep实例。 - 构造函数参数不匹配:调用
make_unique<Sheep>(sheep_pos, *this)时,第二个参数传的是World类型的左值引用,但Sheep的构造函数要求第二个参数是World*指针类型,参数类型不匹配。
修复方案
- 将
Sheep的继承改为公有继承,修改头文件类声明:
class Sheep : public Organism
- 给
Sheep的构造函数添加public权限修饰:
class Sheep : public Organism { public: Sheep(coordinates organism_pos, World* world); };
- 调用
make_unique时将第二个参数改为World指针,替换*this为this:
organism_list.push_back(make_unique<Sheep>(sheep_pos, this));
补充注意:为了保证派生类对象通过基类智能指针释放时能正确调用析构函数,建议给基类
Organism添加虚析构函数:class Organism { public: virtual ~Organism() = default; // 其余原有类定义 };
内容的提问来源于stack exchange,提问作者Michał Turek
相关产品推荐
相关产品推荐

