本文介绍了静态数据成员的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Scott Meyers 的 C++ 并遇到了这个例子:

class GamePlayer{私人的:静态常量 int NumTurns = 5;int score[NumTurns];//...};

您在上面看到的是 NumTurns 的声明,而不是定义.

为什么不是定义?看起来我们用 5 来初始化静态数据成员.

我只是不明白声明但未定义一个值为5的变量是什么意思.我们可以很好地取变量的地址.

A 类{民众:void foo(){ const int * p = &a;}私人的:静态常量 int a = 1;};int主(){一个;a.foo();}

演示

解决方案

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

[class.static.data]/2

static 数据成员在其类定义中的声明不是一个定义并且可能是 cv 限定的不完整类型无效.static 数据成员的定义应出现在包含成员类定义的命名空间范围.

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

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

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

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

解决方案

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

[class.static.data] / 2

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

这篇关于静态数据成员的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 21:34
查看更多