简体   繁体   English

当想要push_back向量列表时,shared_ptr的向量导致错误:“没有重载函数的实例”

[英]Vector of shared_ptr resulting in error: “no instance of overloaded function” when wanting to push_back vector list

I have a smart pointer of a base class to prevent object slicing like so: 我有一个基类的智能指针,以防止像这样的对象切片:

vector<shared_ptr<BaseClass>> vectorOfObjects;

I want to pass this object through a function and then add a derived object to the vector list: 我想通过一个函数传递这个对象,然后将一个派生对象添加到矢量列表:

function(vector<shared_ptr<BaseClass>>& vectorOfObjects) {}

In this function, I create a new derived object that I want to add to the list: 在这个函数中,我创建了一个我想要添加到列表中的新派生对象:

DerivedClass derivedObject = DerivedClass();

vectorOfObjects.push_back(&derivedObject);

I'm getting an error under the dot of the last line above stating 我在上面最后一行的点下面收到一个错误

no instance of overloaded function std::vector<_Ty,_Ax>::pushback
 [with _Ty="std::tr1::shared_ptr<BaseClass>,_Ax=std::allocator<std:
:tr1::shared_ptr<BaseClass>>]" matches the argument list

Any help at all would be much appreciated as I can't seem to find the right solution to pass a vector consisting of a pointer of objects (required to prevent object slicing) through a function. 任何帮助都会非常感激,因为我似乎无法找到通过函数传递由对象指针(需要防止对象切片)组成的向量的正确解决方案。

Use 采用

// DerivedClass derivedObject = DerivedClass(); <<< Not needed
vectorOfObjects.push_back(std::make_shared<DerivedClass>());

There's a number of constructor declarations that allow conversion from a std::shared_ptr<DerivedClass> to std::shared_ptr<BaseClass> . 有许多构造函数声明允许从std::shared_ptr<DerivedClass>std::shared_ptr<BaseClass>


As from your comment 从您的评论中

If I need to make a separate declaration, as I also have a vector member in my BaseClass, how can I declare a derivedObject separately as I have attempted earlier? 如果我需要单独声明,因为我的BaseClass中也有一个向量成员,我如何单独声明一个derivedObject,就像我之前尝试过的那样?

It's not completely clear for me what "as I also have a vector member in my BaseClass" has to do with it, but if you insist you can do: 我并不完全清楚“因为我在我的BaseClass中也有一个矢量成员”与它有关,但如果你坚持你可以这样做:

DerivedClass derivedObject* = new DerivedClass();
// Do special stuff only available in DerivedClass
derivedObject->specialFunc();
vectorOfObjects.push_back(std::shared_ptr<DerivedClass>(derivedObject));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM