0

可能重复:
C++:对静态类成员的未定义引用

以下 C++ 代码编译良好(使用g++ -c),但没有链接给出错误:undefined reference toAbc::X'`

#include <iostream>

using namespace std;

class Abc {

public:
    const static int X = 99;
};

int main()
{
    Abc a1;
    cout << &(Abc::X) << endl;
}

我想知道为什么不允许这样做?

4

3 回答 3

4

您需要实际定义该静态成员,而不仅仅是声明...

在你的之前添加这一行main()

const int Abc::X = 99;

从 C++17 开始,您还可以执行内联静态,在这种情况下,不需要 .cpp 文件中的上述附加代码行:

class Abc {

public:
    inline const static int X = 99; // <-- "inline"
};
于 2012-07-15T07:15:26.053 回答
1

如果您不喜欢考虑翻译单元、静态初始化顺序和类似的东西,只需将您的静态常量更改为方法。

#include <iostream>
using namespace std;

class Abc {

public:
    inline static const int& X(){ 
      static int x=99;
      return x; 
    }
};

int main()
{
//    Abc a1;
    cout << &(Abc::X()) << endl;
}
于 2012-07-15T07:24:55.437 回答
1

如果静态成员以需要左值的方式使用(即以需要它有地址的方式),那么它必须有一个定义。请参阅GCC wiki上的说明,其中包括对标准的引用以及如何修复它。

于 2012-07-15T10:24:03.207 回答