C++ 多路径继承 : Why the access using Base class scope is non-ambiguous?

标签 c++ inheritance virtual-inheritance diamond-problem

我在学习C++,在学习虚继承的过程中,遇到了如下疑惑:

class A {
public:
    int x;
    A() { x = 677; }
    A(int a) { 
        cout << "A con , x= " << a << endl;
        x = a;
    }
};
class B : public A {
public:
    B(int a) : A(a) { }
};
class C :public A {
public:
    C(int a) : A(a) { }
};
class D : public B, public C {
public:
    D(int a,int b) : B(a),C(b) { }
};
int main()
{
    D d(5,6);
    cout << d.A::x;  //prints 5 
 }

在线cout << d.A::x;它打印 5。这个调用不应该是模棱两可的吗?如果不是,为什么它打印 5?

最佳答案

d.A::x; 确实是模棱两可的。 GCC 和 Clang 将其报告为错误,只有 MSCV 没有这样做:https://godbolt.org/z/1zhjdE6a8 .

[class.mi]中有注释以多重继承为例说明:

In such lattices, explicit qualification can be used to specify which subobject is meant. The body of function C​::​f can refer to the member next of each L subobject:

void C::f() { A::next = B::next; }      // well-formed

Without the A​::​ or B​::​ qualifiers, the definition of C​::​f above would be ill-formed because of ambiguity ([class.member.lookup]). — end note]

这只是一个注释,因为它遵循 [class.member.lookup](阅读和理解起来有点做作)没有限定符,成员访问是不明确的。 “格式错误”意味着符合标准的编译器必须发出错误或警告。

关于C++ 多路径继承 : Why the access using Base class scope is non-ambiguous?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69975308/

相关文章:

c++ - 对象层次结构的 "Implementation"- "the easiest way"或如何避免虚拟继承?

c++ - 在虚拟继承中交换和复制成语的正确方法是什么?

c++ - 在代码生成后更改 llvm::Function 签名,在最后一个 CreateRet 之前

java - 在java中使用mockito模拟子类项

C#继承类型转换错误

ruby - 为什么 inspect for the subclasses of built-in classes 中没有列出实例变量?

python - zeromq (zmq) 缺少带有 c++ 发布者和 python 订阅者的消息

c++ - Visual Studio 无法打开包含文件;没有这样的文件或目录

c++ - 使用 Bazel 更改编译器命令行

c++ - 当我从虚拟基派生 D 时,为什么 VS2015 中的 sizeof(D) 增加了 8 个字节?