容器类的成员不能是基类

时间:2017-10-21 21:12:04

标签: c++ base-class

我有一个与其成员一起做事的容器类。该成员应该是派生类,因为它可以有几种类型。我想在这个与该成员一起使用的容器类中编写相同的代码,无论它是什么类型的派生类。但是,我甚至无法让它运行。它编译,但运行时错误是/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;
}

2 个答案:

答案 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>()));

答案 1 :(得分:1)

您需要定义基类虚函数

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

或者如果你想使它成为pure virtual function你不能拥有Base类的实例,所以通过Base* m_thing;

使它保持Base类的指针