You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将派生类对象加入基类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*指针类型,参数类型不匹配。

修复方案

  1. 将Sheep的继承改为公有继承,修改头文件类声明:
class Sheep : public Organism
  1. 给Sheep的构造函数添加public权限修饰:
class Sheep : public Organism
{
public:
    Sheep(coordinates organism_pos, World* world);
};
  1. 调用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:45:03