【发布时间】:2020-03-23 21:11:33
【问题描述】:
我在一个类中,我应该使用抽象基类和派生类的两级层次结构创建共享指针向量。
class Base
{
virtual string returnName() = 0;
};
class DerivedOne : public Base
{
private:
string name;
public:
DerivedOne()
{name = "Derived";}
virtual string returnName()
{return name;}
};
class DerivedTwo : public DerivedOne
{
private:
string secondName;
public:
DerivedTwo()
{secondName = "DerivedTwo";}
virtual string returnName()
{return secondName;}
};
int main()
{
vector<shared_ptr<Base>> entities;
entities.push_back(new DerivedOne());
return 0;
}
我的问题是使用push_back() 将派生类添加到向量的末尾,并在编译时显示no matching function for call to ‘std::vector<std::shared_ptr<Base> >::push_back(DerivedOne*)
如何将初始化的派生类添加到向量中?
【问题讨论】:
-
您可以通过将原始指针转换为
std::shared_ptr来使其工作,因为std::shared_ptrctor 是显式的。但是你最好还是使用std::make_shared()
标签: c++ vector shared-ptr