简体   繁体   English

完全限定的静态成员变量中的歧义

[英]Ambiguity in a fully qualified static member variable

In this sample code, there is two sentences showing the same static variable. 在此示例代码中,有两个句子显示相同的静态变量。 The first one gives no ambiguity, but the second one does, why? 第一个没有歧义,但第二个没有,为什么?

#include <iostream>

using namespace std;

struct A { static const char a = 'a'; };
struct B : public A { };
struct C : public A { };
struct G : public B, public C { };

int main()
{
    G v;

    cout << G::B::A::a << endl;
    cout << v.B::A::a << endl;
}

GCC error (according to some comments, there's no ambiguity in clang): GCC错误(根据一些评论,clang中没有歧义):

main.cpp:15:18: error: 'A' is an ambiguous base of 'G'
  cout << v.B::A::a << endl;

Code on coliru 关于coliru的代码

This is clearly a bug in GCC, as a GCC maintainer recommends you report it. 这显然是GCC中的一个错误,因为GCC维护者建议您报告它。 However, until it's fixed, you can use a nasty workaround like this: 但是,在修复之前,您可以使用这样一个讨厌的解决方法:

std::cout << static_cast<B &>(v).A::a;

The advantage is this will help disambiguate if in a (complex) scenario that there are variables with the same name in one of the base classes. 优点是,如果在(复杂)场景中,在其中一个基类中存在具有相同名称的变量,这将有助于消除歧义。

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

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