静态const成员初始化中的sizeof [英] sizeof in static const member initialization

查看:74
本文介绍了静态const成员初始化中的sizeof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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 ++标准对此有何评论?

I got compiler error in VC++ and no errors in IAR. Which compiler is right, what C++ standart says about it?

推荐答案

您的MSVS版本很旧,因此基于此版本,并假设它们默认为C ++ 03,则拒绝您的代码是正确的.我引用 n1905 ,就我们的目的而言,它非常接近C ++ 03标准.

Your MSVS versions are quite old, so based on that, and assuming they default to C++03, they are correct to reject your code. I'll quote n1905, which for our purposes is pretty close to the C++03 standard.

9.4 [class.static] (强调我的意思)

如果在静态变量的定义中使用了非限定ID(5.1)成员的声明者ID和名称查找之后的成员(3.4.1)发现unqualified-id引用了静态成员枚举器,或成员类的嵌套类型(或成员的班级),则将unqualified-id转换为qualified-id嵌套名称说明符在其中命名类作用域的表达式从中引用该成员.静态成员的定义不得直接使用其非静态成员的名称类或该类的基类(包括作为sizeof运算符).静态成员的定义只能引用这些成员形成指向成员(5.3.1)或与类的指针成员访问语法(5.2.5).

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).

这篇关于静态const成员初始化中的sizeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆