在类定义之外的静态const的定义 [英] definition of static const outside the class definition

查看:94
本文介绍了在类定义之外的静态const的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们应该在类定义之外定义一个 static const 成员,即使它在类中初始化了吗?

Should we define a static const member outside of the class definition even if it is initialised inside the class?

#include<iostream>  
using namespace std;  
class abc  
{  
    static const int period=5;  
    int arr[period];  
  public:  
    void display()   
    {   
        cout<<period<<endl;  
    }  
};

const int abc::period;   

int main()   
{   
    abc a;  
    a.display();   
    return 0;  
}

注释 // const int abc :: period ; ,这两个版本的代码在gcc 4.3.4上运行良好。

After commenting // const int abc::period;, both versions of the code run fine on gcc 4.3.4. So I want to ask why do both versions work and which one is standard compliant?

推荐答案

你是定义


9.4.2 / 4 - 如果静态数据成员是const整数或const枚举类型,它在类定义中的声明可以指定一个常量初始化器,它应是一个整数常量表达式(5.19)。在这种情况下,成员可以出现在整数常数表达式中。

9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.



Your code compiles even without the definition because you are not taking the address of the static member. Bjarne Stroustrup mentions in the C++-FAQ here that You can take the address of a static member if (and only if) it has an out-of-class definition

这篇关于在类定义之外的静态const的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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