无法将变量声明为抽象类型,因为虚函数是纯函数 - 具有多重继承

时间:2017-07-06 14:28:15

标签: c++ inheritance abstract-class abstract

我已经看到了这种问题的多个答案,但我没有得到如何解决它。主要问题可能是我正在研究其他人的代码,但是呃。以下是此问题的简化示例: 我有一个类可以链接许多其他类:

Invoke

在system_atoms中,我有:

class Interface
  : public system_atoms,
    public system_io,
    /* etc, others */
{
/* A few functions, none that matters here - none from the inherited classes redefined */
}

我有一个应继承自Interface的类:

class system_atoms {
public:
    virtual int init_atom(int atom_number) = 0;
    virtual int check_atom_id(int atom_number) = 0;
}

在.cpp:

class Interface_proxy : public Interface {
public: 
/* stuff - no function from the inherited classes redefined */
}

编译带来错误,指出“无法将变量Interface_proxy global_interface_proxy; 声明为抽象类型global_interface_proxy,因为虚函数[system_atoms中列出的两个]是纯”。 / p>

我也不是非常精通c ++。我想我应该将两个虚函数重新定义为纯函数(同样没有Interface_proxy= 0对吗?)某处,以便变量不是抽象类型。但是我的知识在那里停止了 - 多重继承让我感到困惑。

1 个答案:

答案 0 :(得分:4)

pure virtual function是一个虚拟的函数,它显式没有实现(用尾随= 0表示)。纯虚函数旨在强制派生类为该函数提供自己的实现。换句话说,派生类最终应该为该函数定义自己的行为。

抽象类是一个具有一个或多个纯虚函数的类,要么是因为它至少声明了一个,要么它继承自抽象类,并且不会覆盖所有继承的纯虚函数。这些类无法实例化(您无法创建它的实例),因为它们的行为未完全定义。它们只能用作其他类型的基类。

在您的情况下,system_atoms定义了2个纯虚函数,因此它是一个抽象类。您列出的每个继承自system_atoms的类都是抽象的,因为它们都从这些纯虚函数继承而且从不覆盖它们。

正确的解决方案是通过覆盖为派生类中的那些纯虚函数提供实现。

参见virtual functions  和override说明符。

这里没有使用多重继承,除了每个继承的类可能有自己的纯虚函数。只需正常覆盖纯虚函数。