本文介绍了为什么单个虚拟继承不足以解决可怕的钻石问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct B { int i; };
struct D1 : virtual B {};
struct D2 : B {};  // <-- not virtual
struct DD : D1, D2 {};

编译器需要 D2 virtual

DD d;
d.i = 0; // error: request for member `i' is ambiguous

我不明白的是,您提示编译器 B virtual > D1 ),为什么仍然 i 不明确?

What I don't understand is, once you have prompted compiler that B is virtual with respect to DD (via D1) then why it still i is ambiguous ?

(如果我的内存正确,老的VC ++(在2006年)足够能够用单个 virtual 继承)来证明这一点。

(If my memory serves correct, the older VC++ (in 2006), was capable enough to make out this just with single virtual inheritance)

推荐答案

B相对于DD不是虚拟的 - 它相对于D1是虚拟的。在D2被创建时,它包含一个B的完整副本。所以现在DD有两个B的实现:一个作为D2的一部分,一个在结束(由D1指向)。有两个副本 i ,使用它确实是不明确的。

B is not virtual with respect to DD - it is virtual with respect to D1. At the time D2 is created, it contains a full copy of B. So now DD has two implementations of B: one as part of D2, and one at the end (pointed by D1). And having two copies of i, using it is indeed ambiguous.

D2也使用虚拟继承,而不是包含B的副本,它将包含指向D1的实例的指针,D1也指​​向,并且DD将仅包含B的一个实例。

Had D2 also used virtual inheritance, instead of containing a copy of B, it would have contained a pointer to the instance of B that D1 is also pointing at, and DD would have contained only one instance of B.

我会尝试说明内存布局,希望这出来正确...:

I'll try to illustrate the memory layouts, hope this comes out right...:

你的情况下,一个虚拟继承和一个非虚拟 -

Your case, with one virtual inheritance and one non-virtual -

|    D1    |   D2 + B |    B    |
+--+-------+----------+---------+
 |   vptr to B           ^
 +-----------------------|

D1和D2实际上都继承了 -

Having both D1 and D2 inherit virtually -

|   D1   |   D2   |   B   |
+--+-----+---+----+-------+
 |         |         ^
 +---------+---------|

这篇关于为什么单个虚拟继承不足以解决可怕的钻石问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 23:02