我有一個容器類,它的成員做事情。這個成員應該是一個派生類,因爲它可以有幾種類型。我想在此容器類中編寫與此成員一起使用的相同代碼,而不管它是哪種類型的派生類。但是,我甚至無法得到這個運行。它編譯,但運行時錯誤是/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;
}
OK,冷靜,看起來就像我有一些東西要閱讀。謝謝@DanielTrugman – Taylor
@泰勒,玩得開心:) –