Container Class 的成员不能是 Base Class

Member of Container Class Can't be a Base Class

我有一个容器 class 可以处理它的成员。这个成员应该是派生的class,因为它可以有几种类型。我想在此容器 class 中编写与该成员一起使用的相同代码,无论它是什么类型的派生 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;
}

要么你需要定义基础class虚函数

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

或者如果你想让它成为一个 pure virtual function 你不能有 Base class 的实例所以通过做 Base* m_thing;[= 让它持有 Base class 的指针13=]

当你离开这样的原型时:

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