多重继承歧义基类
Multiple inheritance ambiguous base class
考虑以下代码
struct Base{};
struct Derived: public Base{};
struct A: public Base{};
struct B: public A, public Base{};
struct C: public A, public Derived{}; // why no ambiguity here?
int main() {}
编译器(g++5.1)警告
警告:由于歧义
struct B: public A, public Base{};
我明白了,Base
在B
中是重复的。
为什么没有
C
的警告?C
不是同时继承A
和Derived
吗? CC_8和CC_9都继承'Base'
0 ?为什么添加
virtual
struct Derived: virtual Base{};
结果现在B
和C
都发出警告,live on Wandbox
警告:由于
struct B: public A, public Base{};
歧义,'B'
无法访问直接基'Base'
警告:由于
struct C: public A, public Derived{};
歧义,'C'
无法访问直接基'Base'
在'B'
0中,不能引用直接继承的Base
子对象的成员。考虑:
struct Base {
int x;
};
struct B: public A, public Base {
void foo() {
int& x1 = A::x; // OK
int& x2 = x; // ambiguous
// no way to refer to the x in the direct base
}
};
在C
中这不是问题。两个x
都可以使用限定名来引用:
struct C: public A, public Derived {
void foo() {
int& x1 = A::x; // OK
int& x2 = Derived::x; // OK
}
};
所以你得到的警告只有在直接基也通过另一个路径继承时才有意义。
对于你的第二个问题,我无法用g++-5.1在Coliru上复制C
的警告。
无法明确地访问"B"中的Base成员,而在"C"中是可能的,如下面的代码所示:
#include <iostream>
using namespace std;
struct Base
{
void print()
{
cout << "Base" << endl;
}
};
struct Derived : public Base {};
struct A : public Base
{
void print()
{
cout << "A" << endl;
}
};
struct B : public A, public Base
{
void print()
{
A::print();
//error (ambiguous), no way to access to Base::print => warning
//Base::print();
}
};
struct C : public A, public Derived
{
void print()
{
A::print();
Derived::print(); // Not Ambiguous, it's the Base inherited by 'Derived' which is used.
// Still an error but you can access print indirectly through "Derived" => no warning needed
//Base::print();
}
};
int main()
{
B b;
b.print();
C c;
c.print();
return 0;
}
相关文章:
- std::具有相同基类的类的变体
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 基类中的函数名称解析
- C++初始化基类
- 如何通过派生类函数更改基类中的向量
- 如何定义一个纯抽象基类
- 如何使用基类指针引用派生类成员
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么此派生对象无法访问基类的后递减方法?
- 公开最直接的基类模板名称
- 当基类是依赖类型时,这是一个缺陷吗
- 警告:由于歧义而导致的直接基类无法访问;这是严重的
- 在将派生类指针转换为基类时,基类有歧义
- 在类模板中消除基类名称的歧义
- 多重继承歧义基类