我有一个容器类,可以处理其成员的事务。该成员应该是派生类,因为它可以有几种类型。我想在与此成员一起工作的此容器类中编写相同的代码,而不管它是什么类型的派生类。但是,我什至无法运行它。它可以编译,但是运行时错误为/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;
}

最佳答案

当您像这样离开原型时:

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

关于c++ - 容器类的成员不能为基类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46868131/

10-11 22:50
查看更多