Why can't redefine type names in class in C++?

前端 未结 3 1258
星月不相逢
星月不相逢 2020-12-03 23:28

According to the book C++ Primer section, 7.4.1 Type Names Are Special:

Ordinarily, an inner scope can redefine a name from an outer scope even if tha

3条回答
  •  借酒劲吻你
    2020-12-04 00:27

    This is not unique to types. [basic.class.scope]/2:

    A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

    The reason is that name lookup in class scope is a little special. Consider:

    using Foo = int;
    
    struct X {
        Foo a;    // ::Foo, i.e., int
        void meow() { 
            Foo b = a; // X::Foo; error: no conversion from int to char*
        }
        using Foo = char*;
    };
    

    Name lookup in member function bodies considers all class members, whether declared before or after the member function (otherwise, a member function defined in a class definition wouldn't be able to use a data member declared later in the class). The result is that you get two Foos with different meanings, even though they both lexically precede the class member Foo's declaration. This can easily lead to extremely confusing and brittle code, and so the standard bans it.

提交回复
热议问题