假设我有一个 Alcohol 类,它有两个派生类: Wine 和 Beer 。如果我将创建一个继承自 Wine 和 Beer 的 Cider 类会怎么样?
Cider 课程中会出现多少 Alcohol 副本?
我知道可以使用虚拟继承来完成它,但没有它,但会有什么区别?
答案 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));