2014-03-06 44 views
2

我明白,智能指針可以將不同類(但派生自相同基類)的對象存儲在向量中。我無法正常工作。一個簡單的例子;使用智能指針在向量中存儲派生類的實例

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類背景++告訴我,一個指向派生也是一個指針基地,但顯然這個邏輯並不傳輸到智能指針。我該如何解決 ?任何關於如何使用這種方法加快速度的指針都將非常感謝。

編譯器錯誤是:

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>&&}' 

回答

3

Derived私人Base繼承,這意味着Derived has a BaseDerived is a Base。 更改爲

class Derived : public Base 
//    ^^^^^^ 
+0

哎呦,尷尬,謝謝。 –

相關問題