我将以下内容称为"多重继承":
通过继承一个或多个后代,直接继承一次类,间接继承一次或多次
通过继承两个或多个后代来间接继承一个类两次或更多次
我想知道它是否存在以及如何明确地访问嵌入的子对象.
1.)[ 专业C++,2 次编] †中指明了编译程序不能有直接继承其两个直接父类和所述父的父类.这是真的吗?
鉴于a GrandParent
和Parent
,扩展GrandParent
,VC12和g ++允许a GrandChild
直接从两者Parent
和GrandParent
.继承.在VC12和g ++中,可以按如下方式定义这些类:
GrandParent
声明一个int num
数据成员.除继承之外,Parent
声明自己的.除了继承's和s 之外,它还声明了它自己.num
GrandParent
num
GrandChild
num
Parent
GrandParent
num
VC12似乎允许明确的成员访问,但g ++只允许它在某些情况下.
#includeusing 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
g ++中的含糊不清楚(b)gc.Parent::num
不是?(a)唯一地描述它在继承树上的位置.gc
只有1 Parent
个子对象,只有1 个子对象,只有1 GrandParent
个子对象num
.对于(b),gc
有一个Parent
,它有自己的,num
但也有一个GrandParent
子对象与另一个num
.
3.)因为gc.GrandParent::num
,VC12看起来是后者的gc
直接GrandParent
基础子对象num
.我猜这是明确的原因是,它是由合格的名称查找gc
,所以实体的右边.
是寻找第一次gc
的范围,最直接的GrandParent
到gc
的范围是直接继承的,不是间接地继承了一个Parent
.我错了吗?
4.)为什么不是gc.GrandParent::num
g ++时gc.Parent::num
不明确 ?如果一个人含糊不清,那么两者是否应该同样含糊不清?对于先前,gc
有两个GrandParent
; 对于后者,Parent
有2 num
秒.
† Gregoire,Marc R.等.专业的C++,2 次编辑.印第安纳波利斯,印第安纳州:Wiley Pubishing,2011年.241.打印.