静态数据成员的定义

Definition of the static data member

我正在阅读 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.

为什么不定义?看起来我们用 5.

初始化了静态数据成员

我只是不明白什么是声明但没有定义一个值为5的变量。我们可以取变量的地址。

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

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

DEMO

你需要在源文件中定义NumTurns,比如

const int GamePlayer::NumTurns;

因为它不是定义。静态数据成员必须在 class 定义之外定义。

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

至于在没有实际定义的情况下获取静态成员的地址,它会编译,但它不应该 link。