且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不能在 C++ 中重新定义类中的类型名称?

更新时间:2021-09-07 01:58:44

这不是类型独有的.[basic.class.scope]/2:

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

在类S中使用的名称N应在其上下文以及在 S 的完整范围内重新评估时.不违反此规则需要进行诊断.

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*;
};

成员函数体中的名称查找考虑所有类成员,无论是在成员函数之前还是之后声明(否则,在类定义中定义的成员函数将无法使用在类中稍后声明的数据成员).结果是您得到两个具有不同含义的 Foo ,即使它们在词法上都在类成员 Foo 的声明之前.这很容易导致非常混乱和脆弱的代码,因此标准禁止它.

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.