问题
I'm trying to access the member variable x in struct Top using a Bottom object.
The code is the following:
#include <cstdio>
struct Top
{
public:
int x = 1;
};
struct Left : public Top
{
int x = 2;
};
struct Right : public Top
{
int x = 3;
};
struct Bottom : public Left, public Right
{
int x = 4;
};
int main()
{
Bottom b;
std::printf("value: %d\n", b.Left::Top::x);
return 0;
}
This gives the following error using gcc 4.8:
main.cpp: In function 'int main()':
main.cpp:27:45: error: 'Top' is an ambiguous base of 'Bottom'
std::printf("value: %d\n", b.Left::Top::x);
^
How is this ambiguous and how do I access it with a qualified name?
回答1:
The problem is that C++ has no way to directly express the concept of "multiple-level" class members, such as "the member x
of the Top
subobject of Left
". What Left::Top::x
means is "the member x
in the type denoted by Left::Top
" - and the type denoted by Left::Top
is exactly Top
.
This is why you can write odd things like
int Left::* ptr = &Right::Top::x;
because the right hand side of the =
is exactly equivalent to &Top::x
, and a pointer-to-base-class-member is implicitly convertible to a pointer-to-derived-class-member. (The result of this conversion still refers to the member in the base-class subobject of the derived class.)
To disambiguate, you can either do something along the lines of static_cast<Left &>(b).Top::x
or use a pointer-to-member - given int Left::* ptr = &Top::x;
, b.*ptr
will refer to the x
in the Top
subobject of the Left
subobject of b
.
来源:https://stackoverflow.com/questions/25952681/when-using-multiple-inheritance-why-is-this-qualified-name-ambiguous