When using multiple inheritance, why is this qualified name ambiguous?

后端 未结 1 776
余生分开走
余生分开走 2021-02-15 10:45

I\'m trying to access the member variable x in struct Top using a Bottom object.

The code is the following:

#include 

        
相关标签:
1条回答
  • 2021-02-15 11:25

    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.

    0 讨论(0)
提交回复
热议问题