c++ - 如果一个父类是一个接口(interface),可以使用多重继承吗?

标签 c++ inheritance multiple-inheritance virtual-functions

enter image description here

如果一个父类是一个接口(interface)(仅包含带有虚拟析构函数的纯虚函数),可以使用多重继承吗?

我只想公开接口(interface)部分(图中的黄色类)以提高编译速度。绿色部分是实现部分。但CPet应该继承自CAnimal(is-a relation)和IPet(implement),有“死亡钻石”:(

接口(interface)类(黄色)只有纯虚函数和虚析构,所以当我通过工厂类创建CDog、CCat时,不存在歧义等问题。 CDog 有两个虚函数表(IDog 和 CPet),但在虚函数表中,点表示相同的函数(CDog 成员函数)。

没有编译错误,没有运行错误...但我担心这个层次结构。 可以吗还是有什么问题吗?

PS:我不想使用“虚拟继承”,因为如果我使用它,我无法通过监视 View 查看类成员变量。(我猜这是因为虚拟继承链接到父类,如链接-列表。)

环境:Visual Studio C++ 2008 或更高版本。

最佳答案

根据上面的描述,您应该无法实例化 CPet 的实例,因为纯虚函数 IAnimal::isAlive() 中未定义IPet vtable。

struct IAnimal {
    virtual ~IAnimal() {}
    virtual void isAlive() = 0;
};

struct IPet : public IAnimal {
};

struct CAnimal : public IAnimal {
    virtual void isAlive() {
    }
};

struct CPet : public CAnimal, public IPet {
};

int main(void) {
    CPet cp;
}

使用 Visual C++ 2008 和 2010 编译时生成以下内容:

animal.cpp(18) : error C2259: 'CPet' : cannot instantiate abstract class
    due to following members:
    'void IAnimal::isAlive(void)' : is abstract
    mytest.cpp(5) : see declaration of 'IAnimal::isAlive'

GCC 会产生类似的警告:

animal.cpp: In function 'int main()':
animal.cpp:18:7: error: cannot declare variable 'cp' to be of abstract type 'CPet'
animal.cpp:14:8: note:   because the following virtual functions are pure within 'CPet':
animal.cpp:3:15: note:  virtual void IAnimal::isAlive()

关于c++ - 如果一个父类是一个接口(interface),可以使用多重继承吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10569499/

相关文章:

database - 继承变坏了吗?

python - python 中的多重继承以及向继承类传递参数

c++ - 多重继承层次结构

c++ - 如何将 System::WideString 转换为 char*,反之亦然?

C++ new 运算符继承和内联数据结构

java - 抽象父类(super class)中的 protected 字段是否应该在子类中使用 super 或 this 来访问?

java - 我应该@Deprecate 父类(super class)方法吗?

c++ - 需要一些帮助解决两个错误 (C++)

c++ - 链接器故障 : How to determine where a "/DEFAULTLIB" is coming from

c++ - 在 aux 方法中创建的 QWidget 不显示/绘制