一个继承自c ++中两个类的类

时间:2016-05-23 21:34:04

标签: c++ oop inheritance abstract-class multiple-inheritance

假设我有一个 Alcohol 类,它有两个派生类: Wine Beer 。如果我将创建一个继承自 Wine Beer Cider 类会怎么样?

Cider 课程中会出现多少 Alcohol 副本?

我知道可以使用虚拟继承来完成它,但没有它,但会有什么区别?

1 个答案:

答案 0 :(得分:13)

非虚拟继承:

struct Beer : Alcohol {};
struct Wine : Alcohol {};           // I'll have what he's having!
Alcohol   Alcohol                   // ...whe-ere'sh my... bayshe clashhh... hic
   ^         ^
   |         |
 Beer       Wine
    ^       ^
     \     /
      \   /
      Cider

虚拟继承:

struct Beer : virtual Alcohol {};   // virtual = doesn't get you drunk
struct Wine : virtual Alcohol {};
     Alcohol                        // you can see clearly now
     ^     ^
    /       \
 Beer       Wine
    ^       ^
     \     /
      \   /
      Cider

在非虚拟情况下,有两个不同的基础子对象。让我们来看看他们:

Cider x;
Alcohol & a1 = static_cast<Beer&>(x);
Alcohol & a2 = static_cast<Wine&>(x);

assert(std::addressof(a1) != std::addressof(a2));