[英]Push_back shared_ptr of derived class
I cannot understand what is going on with my code: why I get a "no matching function for call to push_back" error. 我不明白我的代码发生了什么:为什么我收到“没有匹配的函数来调用push_back”错误。 I can only guess it is a newby mistake...
我只能猜测这是一个新错误。
int main(){
typedef std::tr1::shared_ptr<Base> Base_p;
typedef std::vector<Base_p> VectorPointers_t;
std::tr1::shared_ptr<Derived> myDer01(Derived);
VectorPointers_t myVector = VectorPointers_t();
myVector.push_back(myDer01);
}
Try this: 尝试这个:
VectorPointers_t myVector;
myVector.push_back(Base_p(new Derived));
There is a big error in your code: The line declaring myDer01
actually declares a function and not aa variable. 您的代码中有一个大错误:声明
myDer01
的行实际上声明了一个函数而不是一个变量。 But even if you had written (Derived())
instead of Derived
it would have been wrong, since you cannot construct a shared pointer from an object — only from a pointer! 但是,即使您编写了
(Derived())
而不是Derived
也将是错误的,因为您不能从对象构造共享指针,而只能从指针构造! So you really want to say new Derived
. 所以您真的要说
new Derived
。
shared_ptr is a class template and each invocation of that template with different parameters will result in a separate class. shared_ptr是一个类模板,使用不同参数的该模板的每次调用将导致一个单独的类。 The solution is to create only shared pointers to the base class.
解决方案是仅创建指向基类的共享指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.