2017-10-21 61 views
0

我有一個容器類,它的成員做事情。這個成員應該是一個派生類,因爲它可以有幾種類型。我想在此容器類中編寫與此成員一起使用的相同代碼,而不管它是哪種類型的派生類。但是,我甚至無法得到這個運行。它編譯,但運行時錯誤是/bin/sh: ./virtual_member_test: No such file or directory。這是一些示例代碼。爲什麼這不起作用?集裝箱類的成員不能是基類

#include <iostream> 
#include <string> 

class Base 
{ 
public: 
    Base(); 
    ~Base(); 
    virtual void foo(std::string s); // also tried making this pure virtual but doesn't compile 
}; 

class Derived1 : public Base 
{ 
public: 
    Derived1(); 
    ~Derived1(); 
    void foo(std::string s) {std::cout << s << " 1" << std::endl;}; 
}; 

class Derived2 : public Base 
{ 
public: 
    Derived2(); 
    ~Derived2(); 
    void foo(std::string s) {std::cout << s << " 2" << std::endl;}; 
}; 

class Container 
{ 
public: 
    Base m_thing; 
    Container(Base thing); 
    ~Container(); 
}; 

Container::Container(Base thing) : m_thing(thing) 
{ 
} 

int main(int argc, char **argv) 
{ 
    return 0; 
} 

回答

4

當你離開的原型是這樣的:

virtual void foo(std::string s); 

該方法未定義,因此鏈接器不滿意。

當您更改原型,以這樣的:

virtual void foo(std::string s) = 0; 

的方法是一個純虛擬的,編譯器將不允許Base實例的創建,因此編譯器是生氣。

相反,如果你想使用多態,你應持有指針Base而不是一個實例:

class Container 
{ 
public: 
    std::shared_ptr<Base> m_thing; 
    Container(std::shared_ptr<Base> thing) : m_thing(thing) {} 
}; 

而且使用創建Container實例:

Container container(std::static_pointer_cast<Base>(std::make_shared<Derived1>())); 
+0

OK,冷靜,看起來就像我有一些東西要閱讀。謝謝@DanielTrugman – Taylor

+1

@泰勒,玩得開心:) –

2

要麼你需要定義的基類的虛函數

virtual void foo(std::string s){}

,或者如果你想成爲一個pure virtual function你不能有基類的實例,以使其持有的基類指針通過做Base* m_thing;

相關問題