我有这样的代码:
class A
{
public:
unsigned long a;
static const unsigned long b = sizeof(a); // "error C2327: 'A::a' : is not a type name, static, or enumerator" in VC++
};
我在 VC++ 中遇到编译器错误,而在 IAR 中没有错误。 哪个编译器是正确的,C++ 标准是怎么说的?
最佳答案
您的 MSVS 版本很旧,因此基于此,并假设它们默认为 C++03,它们拒绝您的代码是正确的。我会引用 n1905 ,就我们的目的而言,它非常接近 C++03 标准。
9.4 [class.static] (emphasis mine)
If an unqualified-id (5.1) is used in the definition of a static member following the member’s declarator-id, and name lookup (3.4.1) finds that the unqualified-id refers to a static member, enumerator, or nested type of the member’s class (or of a base class of the member’s class), the unqualified-id is transformed into a qualified-id expression in which the nested-name-specifier names the class scope from which the member is referenced. The definition of a static member shall not use directly the names of the non-static members of its class or of a base class of its class (including as operands of the sizeof operator). The definition of a static member may only refer to these members to form pointer to members (5.3.1) or with the class member access syntax (5.2.5).
关于c++ - 静态常量成员初始化中的sizeof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53520397/