简体   繁体   中英

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.

In C++, name-lookup happens before member access checking is performed. 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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