简体   繁体   English

静态数据成员的定义

[英]Definition of the static data member

I'm reading Scott Meyers' C++ and come across this example: 我正在阅读Scott Meyers的C ++,并遇到以下示例:

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

What you see above is a declaration for NumTurns , not a definition. 上面看到的是NumTurns的声明,而不是定义。

Why not a definition? 为什么不定义? It looks like we initialize the static data member with 5. 看起来我们用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. 我只是不明白声明什么意思,但没有定义值为5的变量。我们可以将变量的地址设为罚款。

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

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

DEMO DEMO

Because it isn't a definition. 因为这不是一个定义。 Static data members must be defined outside the class definition. 静态数据成员必须在类定义之外定义。

[class.static.data] / 2 [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 . static数据成员的类定义中的声明不是定义,并且可以是cv限定的void之外的不完整类型。 The definition for a static data member shall appear in a namespace scope enclosing the member's class definition. static数据成员的定义应出现在包含该成员的类定义的名称空间范围中。

As for taking the address of your static member without actually defining it, it will compile, but it shouldn't link. 至于在没有实际定义的情况下获取静态成员的地址,它将进行编译,但不应链接。

您需要在源文件中放入NumTurns的定义,例如

const int GamePlayer::NumTurns;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM