[英]Using smart pointers to store instances of a derived class in a vector
I understand that smart pointers make it possible to store objects of different class (but derived from the same base class) in a vector. 我知道,智能指针可以将不同类(但从相同基类派生)的对象存储在向量中。 I am having trouble getting this to work.
我很难让它工作。 A simple example;
一个简单的例子;
class Base
{
public:
virtual void disp() { printf("Base class\n"); }
};
class Derived : Base
{
public:
virtual void disp() { printf("Derived class\n"); }
};
static void test()
{
std::vector< std::shared_ptr<Base> > v;
std::shared_ptr<Base> pa( new Base() );
std::shared_ptr<Derived> pb( new Derived() );
v.push_back(pa);
v.push_back(pb); // compile error wants, std::shared<Base> not Derived
v[0]->disp();
v[1]->disp();
}
My background with simple, "C with classes" type C++ tells me that a pointer to Derived is also a pointer to Base, but apparently this logic doesn't transfer to smart pointers. 我用简单的背景,“带类的C”型C ++告诉我,一个指向派生也是一个指针基地,但显然这个逻辑并不传输到智能指针。 How do I fix this ?
我该如何解决 ? Any pointers on getting up to speed with this approach in general would be much appreciated.
一般情况下,任何有关加快使用此方法的指示都将不胜感激。
The compiler error is: 编译器错误是:
main.cpp: In function 'void test()':
main.cpp:23:19: error: no matching function for call to 'std::vector<std::shared_ptr<Base> >::push_back(std::shared_ptr<Derived>&)'
v.push_back(pb); // compile error wants, std::shared<Base> not Derived
^
main.cpp:23:19: note: candidates are:
In file included from /usr/local/include/c++/4.8.2/vector:64:0,
from main.cpp:2:
/usr/local/include/c++/4.8.2/bits/stl_vector.h:901:7: note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::shared_ptr<Base> _Alloc = std::allocator<std::shared_ptr<Base> > std::vector<_Tp, _Alloc>::value_type = std::shared_ptr<Base>]
push_back(const value_type& __x)
^
/usr/local/include/c++/4.8.2/bits/stl_vector.h:901:7: note: no known conversion for argument 1 from 'std::shared_ptr<Derived>' to 'const value_type& {aka const std::shared_ptr<Base>&}'
/usr/local/include/c++/4.8.2/bits/stl_vector.h:919:7: note: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = std::shared_ptr<Base> _Alloc = std::allocator<std::shared_ptr<Base> > std::vector<_Tp, _Alloc>::value_type = std::shared_ptr<Base>]
push_back(value_type&& __x)
^
/usr/local/include/c++/4.8.2/bits/stl_vector.h:919:7: note: no known conversion for argument 1 from 'std::shared_ptr<Derived>' to 'std::vector<std::shared_ptr<Base> >::value_type&& {aka std::shared_ptr<Base>&&}'
Derived
private inherit from Base
which means Derived has a Base
not Derived is a Base
. Derived
自Base
私有继承,这意味着Derived has a Base
而Derived is a Base
。 Change to 改成
class Derived : public Base
// ^^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.