Definition of the static data member

喜你入骨 提交于 2019-12-11 02:43:36

问题


I'm reading Scott Meyers' C++ and come across this example:

class GamePlayer{
private:
    static const int NumTurns = 5;
    int scores[NumTurns];
    // ...
};

What you see above is a declaration for NumTurns, not a definition.

Why not a definition? It looks like we initialize the static data member with 5.

I just don't understand what it means to declare but not define a variable with the value 5. We can take the address of the variable fine.

class A
{
public:
    void foo(){ const int * p = &a; }
private:
    static const int a = 1;
};

int main ()
{
    A a;
    a.foo();
}

DEMO


回答1:


Because it isn't a definition. Static data members must be defined outside the class definition.

[class.static.data] / 2

The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition.

As for taking the address of your static member without actually defining it, it will compile, but it shouldn't link.




回答2:


you need to put a definition of NumTurns in source file, like

const int GamePlayer::NumTurns;


来源:https://stackoverflow.com/questions/30929941/definition-of-the-static-data-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!