我有一个容器类,它的成员做事情。这个成员应该是一个派生类,因为它可以有几种类型。我想在此容器类中编写与此成员一起使用的相同代码,而不管它是哪种类型的派生类。但是,我甚至无法得到这个运行。它编译,但运行时错误是/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
@泰勒,玩得开心:) –