简体   繁体   English

C ++多重继承私有成员的ambigious访问

[英]C++ multiple inheritance private member ambigious access

The following code: 以下代码:

class A1 {
public:
    int x;
};
class A2 {
private:
    int x() { return 67; }
};

class M : public A1, public A2 {};

int main() {
    M m;
    m.x;
}

Compiles with error: 编译错误:

error C2385: ambiguous access of 'x'
note: could be the 'x' in base 'A1'
note: or could be the 'x' in base 'A2'

But why? 但为什么? only A1::x should be visible to M. A2::x should be purely local. 只有A1::x应该对M可见A2::x应该是纯粹的本地。

In C++, name-lookup happens before member access checking is performed. 在C ++中, 名称查找在执行成员访问检查之前发生。 Hence, name-lookup (Unqualified in your case) finds two names, and that's ambiguous. 因此,名称查找(在您的情况下不合格)找到两个名称,这是不明确的。

You can use a qualified name to disambiguate: 您可以使用限定名称来消除歧义:

int main() {
    M m;
    m.A1::x;     //qualifed name-lookup
}

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

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