Vector of shared_ptr resulting in error: "no instance of overloaded function" when wanting to push_back vector list
Vector of shared_ptr resulting in error: "no instance of overloaded function" when wanting to push_back vector list
我有一个基数的智能指针 class 来防止像这样的对象切片:
vector<shared_ptr<BaseClass>> vectorOfObjects;
我想通过一个函数传递这个对象,然后将派生对象添加到向量列表中:
function(vector<shared_ptr<BaseClass>>& vectorOfObjects) {}
在此函数中,我创建了一个要添加到列表中的新派生对象:
DerivedClass derivedObject = DerivedClass();
vectorOfObjects.push_back(&derivedObject);
我在上面最后一行的圆点下遇到错误
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
任何帮助将不胜感激,因为我似乎无法找到正确的解决方案来通过函数传递由对象指针组成的向量(防止对象切片需要)。
使用
// DerivedClass derivedObject = DerivedClass(); <<< Not needed
vectorOfObjects.push_back(std::make_shared<DerivedClass>());
有许多 constructor declarations 允许从 std::shared_ptr<DerivedClass>
转换为 std::shared_ptr<BaseClass>
。
从你的
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?
我不是很清楚 "as I also have a vector member in my BaseClass" 与它有什么关系,但如果你坚持你可以这样做:
DerivedClass derivedObject* = new DerivedClass();
// Do special stuff only available in DerivedClass
derivedObject->specialFunc();
vectorOfObjects.push_back(std::shared_ptr<DerivedClass>(derivedObject));
我有一个基数的智能指针 class 来防止像这样的对象切片:
vector<shared_ptr<BaseClass>> vectorOfObjects;
我想通过一个函数传递这个对象,然后将派生对象添加到向量列表中:
function(vector<shared_ptr<BaseClass>>& vectorOfObjects) {}
在此函数中,我创建了一个要添加到列表中的新派生对象:
DerivedClass derivedObject = DerivedClass();
vectorOfObjects.push_back(&derivedObject);
我在上面最后一行的圆点下遇到错误
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
任何帮助将不胜感激,因为我似乎无法找到正确的解决方案来通过函数传递由对象指针组成的向量(防止对象切片需要)。
使用
// DerivedClass derivedObject = DerivedClass(); <<< Not needed
vectorOfObjects.push_back(std::make_shared<DerivedClass>());
有许多 constructor declarations 允许从 std::shared_ptr<DerivedClass>
转换为 std::shared_ptr<BaseClass>
。
从你的
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?
我不是很清楚 "as I also have a vector member in my BaseClass" 与它有什么关系,但如果你坚持你可以这样做:
DerivedClass derivedObject* = new DerivedClass();
// Do special stuff only available in DerivedClass
derivedObject->specialFunc();
vectorOfObjects.push_back(std::shared_ptr<DerivedClass>(derivedObject));