简体   繁体   English

来自多重继承的多重继承

[英]Multiple inheritance from multiple inheritance

#include<iostream>
using namespace std;

class base1{
public:
    int x;
};
class base2{
public:
    int x;
};

class derived1: public base1, public base2{
    // Contains...  base1::x, base2::x
};
class derived2: public base1, public base2{
    // Contains...  base1::x, base2::x 
};

class derived: public derived1, public derived2{

};

If I am right, the class derived will contain four integers. 如果我是对的, derived的类将包含四个整数。 But I can't access them with 但是我无法使用
derived1::base1::x, derived1::base2::x, derived2::base1::x, derived2::base2::x


It shows ambiguity error. 它显示了歧义错误。 ('base1' is ambiguous base of 'derived')
Am I missing something? 我想念什么吗? How should I resolve this? 我该如何解决?

Well, when you use the scope resolution operator to disambiguate between members, you don't name a "path" to the member. 好吧,当您使用范围解析运算符消除成员之间的歧义时,您无需为成员指定“路径”。 You instead name, however indirectly, the base class where the member comes from. 相反,您可以间接命名成员所属的基类。

Since the class name is injected into the scope of the class, and as a result, into the scope of any class that derives from it, you are just naming base1 and base2 in a verbose manner. 由于将类名注入到该类的范围内,并且因此,将其注入到任何派生自该类的类的范围内,因此您base1冗长的方式命名了base1base2 Ie all the following are equivalent for the member access: 即,以下所有条件对于成员访问都是等效的:

derived d;
d.base1::x;
d.derived1::base1::x;
d.derived1::derived1::base1::base1::x;

That's why the ambiguity occurs. 这就是产生歧义的原因。 The way to do it, is to cast the object into a derived1& or derived2& , and then use member access via base1::x and base2::x on that. 要做到这一点,是将对象转换derived1&derived2& ,然后通过使用成员访问base1::xbase2::x上。

static_cast<derived1&>(d).base1::x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM