【问题标题】:Adding derived class object to vector<unique_ptr> of base class将派生类对象添加到基类的vector<unique_ptr>
【发布时间】:2021-11-26 19:33:21
【问题描述】:

所以在我的代码中,我试图将unique_ptr 添加到从derived 类到基类vector 的对象中。我收到此错误:

E0304 没有重载函数实例 "std::vector<_ty _alloc>::push_back [with _Ty=std::unique_ptr>, _Alloc=std::allocator>>]" 匹配参数列表

基类的代码(如果需要更多请告诉我,尽量少写代码):

vector<unique_ptr<Organism>>  World::generate_organisms(int act_level)
{
    vector<unique_ptr<Organism>> organism_list = get_vector();
    coordinates sheep_pos(10, 2);
    //getting error in next line
    organism_list.push_back(make_unique<Sheep>(sheep_pos, *this));

    return organism_list;
}

派生类代码:

.h文件

class Sheep : Organism
{
    Sheep( coordinates organism_pos, World* world);
};

.cpp文件

Sheep::Sheep( coordinates organism_pos, World* act_world)
    :
    Organism(organism_pos, act_world)
{
    this->armor = 0;
    this->damage = 2;
    this->health = 10;
    this->vigor = 10;
}

【问题讨论】:

  • 你忘记从 Organism 公开继承了。

标签: c++ c++11 inheritance unique-ptr derived-class


【解决方案1】:

类似于class 的默认成员可见性是private,除非另有说明,否则继承也是private。您需要从 Organism publicly 继承,以便 std::unique_ptr 能够看到并执行您期望的转换。

class Sheep : public Organism {
public:
    Sheep( coordinates organism_pos, World* world);
}

您的构造函数还需要为public,以便std::make_unique 可以看到和使用它。

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 2019-02-17
    相关资源
    最近更新 更多