[英]How do references resolve the ambiguity in multiple inheritance?
The following code shows the notorious diamond inheritance. 以下代码显示了臭名昭著的菱形继承。 But it seems that an appropriate reference designation avoids the ambiguity. 但是似乎适当的参考名称可以避免歧义。
# include <iostream>
# include <stdio.h>
class B {
public:
int m_a ;
} ;
class D1 : public B { } ;
class D2 : public B { } ;
class E : public D1, public D2 { } ;
int main () {
E e ;
D1& c = e ;
D2& d = e ;
e.D1::m_a = 2 ;
e.D2::m_a = 2 ;
std::cout << c.m_a << std::endl ;
std::cout << d.m_a << std::endl ;
c.m_a = 3 ;
std::cout << c.m_a << std::endl ;
std::cout << d.m_a << std::endl ;
printf ( "%p\n", &c ) ;
printf ( "%p\n", &d ) ;
printf ( "%p\n", &e ) ;
printf ( "\n" ) ;
printf ("%p\n", (void*) &(c.m_a)) ;
printf ("%p\n", (void*) &(d.m_a)) ;
return 0 ;
}
The output is: 输出为:
2
2
3
2
0xffffcbf0
0xffffcbf4
0xffffcbf0
0xffffcbf0
0xffffcbf4
So it seems that a reference 'knows' where it should start in the memory layout of the object 'e' which contains duplicated D1::m_a and D2::m_a . 因此,似乎引用“知道”它应该从对象“ e”的内存布局开始的地方,该对象包含重复的D1 :: m_a和D2 :: m_a。 I wonder how it is achieved in C++ implementation. 我想知道如何在C ++实现中实现它。 Thanks! 谢谢!
The easiest way to discover what's happening is by printing (void*)(&c)
and (void*)(&d)
. 发现正在发生的事情的最简单方法是打印(void*)(&c)
和(void*)(&d)
。 The two references refer to distinct subobjects of e
. 这两个参考文献引用了e
不同子对象。
Also, the references to D1
and D2
do not know they're inside some E
. 另外,对D1
和D2
的引用也不知道它们在E
。 A reference can refer to any object in memory, but it doesn't know about the surroundings of that object. 引用可以引用内存中的任何对象,但不知道该对象的周围环境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.