c++ - 使用智能指针将派生类的实例存储在 vector 中

标签 c++

我知道智能指针可以在 vector 中存储不同类(但派生自同一基类)的对象。我很难让它发挥作用。一个简单的例子;

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();
}

我的背景是简单的“带有类的 C”类型 C++,它告诉我指向 Derived 的指针也是指向 Base 的指针,但显然这种逻辑不会转移到智能指针。我该如何解决 ?任何有关如何快速掌握这种方法的建议将不胜感激。

编译器错误是:

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 privateBase 继承,这意味着 Derived 有一个 Base 而不是 Derived 是一个 Base 。 更改为

class Derived : public Base
//              ^^^^^^

关于c++ - 使用智能指针将派生类的实例存储在 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22238724/

相关文章:

c++ - 如何用C++模拟鼠标光标移动

c++ - C 和 C++ 中的 Sizeof

c++ - Xbox Controller 两个拇指棒都没有改变值,使用 Xinput

c++ - std::reference_wrapper 解开包装器

c++ - LLVM-如何使嵌套函数查看外部函数的变量

c++ - 了解 std::hardware_破坏性_interference_size 和 std::hardware_constructive_interference_size

c++ - 为什么我的子类被认为是抽象类?

c++ - 括号与花括号

c++ - 没有线程的命令队列

c++ - 在 C++ 中处理几乎所有的异常