What does C++ syntax “A::B:A {};” mean

前端 未结 2 1676
谎友^
谎友^ 2020-12-23 12:57

What does C++ syntax struct A::B:A {}; mean? Where is this name definition (or access) described in the C++ standard?

#include 
         


        
2条回答
  •  鱼传尺愫
    2020-12-23 13:57

    First of all struct B; is a forward declaration of struct B in global namespace. It might be confusing because it is actually not relevant in this example. This global B can be accessed as ::B or as just B.

    struct A {
        struct B;
    };
    

    Is a definition of struct A in global namespace with a forward declaration of nested struct B (not the same as previously declared B in global namespace). This nested B can be accessed as ::A::B or A::B.

    struct A::B:A {
    };
    

    Is a definition of nested struct B of struct A that inherits from A (with access specifier omitted). It can be rewritten to:

    struct A::B
    :   public A
    {
    };
    

    Note that writing definition of nested struct B inside of A definition like this won't work:

    struct A {
        struct B: A { // error: A is incomplete at this point
        };
    };
    

    And finally A::B::A is referring to the base class of nested struct B, that is to A, so A::B::A::B is equivalent to just A::B.

提交回复
热议问题