我将以下称为“多重重新继承”:
- 直接继承一个类一次,并通过继承其一个或多个后代来间接继承一次或多次
- 通过继承一个类的两个或多个后代来间接继承一个类两次或多次
我想知道它是否存在以及如何明确访问嵌入的子对象。
1.) [Professional C++, 2nd ed.]† states a compilable program can't have a class that directly inherits both its immediate parent and said parent's parent class. Is it true?
Given a GrandParent
and Parent
,这延伸了GrandParent
、VC12 和 g++ 允许GrandChild
直接继承两者Parent
and GrandParent
。在 VC12 和 g++ 中,可以按如下方式定义这些类:
GrandParent
声明一个int num
数据成员。Parent
宣布自己的num
除了继承GrandParent
's num
. GrandChild
宣布自己的num
除了继承Parent
's and GrandParent
's num
s.
VC12 似乎允许全面明确的成员访问,但 g++ 只允许在某些情况下使用。
#include <iostream>
using std::cout;
using std::endl;
struct GrandParent { int num; };
struct Parent : GrandParent { int num; };
struct GrandChild : GrandParent, Parent { int num; };
int main()
{
GrandChild gc;
gc.num = 2;
gc.Parent::num = 1;
gc.Parent::GrandParent::num = 0; // g++ error: ‘GrandParent’ is an ambiguous base of ‘GrandChild’
gc.GrandParent::num = 5; // g++ error: ‘GrandParent’ is an ambiguous base of ‘GrandChild’
// --VC12 output; g++ output--
cout << gc.num << endl; // 2 ; 2
cout << gc.Parent::num << endl; // 1 ; 1
cout << gc.Parent::GrandParent::num << endl; // 0 ; N/A due to above error
cout << gc.GrandParent::num << endl; // 5 ; N/A due to above error
}
2.) 为什么是(a)gc.Parent::GrandParent::num
当 (b) 时,g++ 中不明确gc.Parent::num
不是吗? (a) 唯一地描述了它在继承树上的位置。gc
只有 1 个Parent
子对象,只有 1GrandParent
子对象,只有 1num
。对于(b),gc
有一个Parent
,它有自己的num
但也是一个GrandParent
子对象与另一个num
.
3.) For gc.GrandParent::num
,看来 VC12 正在研究gc
是即时的GrandParent
后者的基础子对象num
。我猜它之所以明确是因为它是由以下条件限定的名称查找gc
,所以右边的实体.
首先在中查找gc
的范围,以及最直接的GrandParent
to gc
的作用域是直接继承的作用域,而不是通过间接继承的作用域Parent
。我错了吗?
4.) 为什么是gc.GrandParent::num
与 g++ 不明确时gc.Parent::num
不是吗?如果其中一个是模棱两可的,那么两者不应该同样模棱两可吗?对于之前的情况,gc
有两个GrandParent
s;对于后者,Parent
has 2 num
s.
†Gregoire, Marc R. et al. Professional C++, 2nd ed. Indianapolis, IN: Wiley Pubishing, 2011. p. 241. Print.