Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c++ - definition of static const outside the class definition

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are defining the static memberperiod by writing const int abc::period;. You are allowed to provide an in class initializer for static const member of a class but that's not definition, but that's merely a declaration.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...