c++ - 在类定义中定义静态常量整数成员

标签 c++ static declaration definition

我的理解是 C++ 允许在类中定义静态常量成员,只要它是整数类型即可。

那么,为什么下面的代码会给我一个链接器错误?

#include <algorithm>
#include <iostream>

class test
{
public:
    static const int N = 10;
};

int main()
{
    std::cout << test::N << "\n";
    std::min(9, test::N);
}

我得到的错误是:

test.cpp:(.text+0x130): undefined reference to `test::N'
collect2: ld returned 1 exit status

有趣的是,如果我注释掉对 std::min 的调用,代码编译和链接就很好(即使在前一行中也引用了 test::N)。

知道发生了什么事吗?

我的编译器是 Linux 上的 gcc 4.4。

最佳答案

My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.

你说的有点对。您可以在类声明中初始化静态常量积分,但这不是定义。

Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line).

Any idea as to what's going on?

std::min 通过 const 引用获取其参数。如果按值取值,则不会出现此问题,但由于您需要引用,因此还需要定义。

这是章节/诗句:

9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

有关可能的解决方法,请参阅 Chu 的回答。

关于c++ - 在类定义中定义静态常量整数成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286645/

相关文章:

c++ - 如何创建自己的 TCP 连接(只需发送 TCP 请求并获得结果)?

c++ - WriteConsoleOutputCharacterW-我的新行在哪里?

c++ - 非静态成员函数的 decltype 格式不正确吗?

c++ - 使用 const getter 风格的函数代替静态数据成员

javascript - 可以在变量声明中添加条件吗?

javascript - 为什么函数在构造函数中声明时不使用 new 关键字?

c++ - MessageBox "Abnormal program termination"让我的应用程序保持运行

objective-c - Objective C/C静态方法性能

c# - 在表单之间传递数据和调用函数而不必将它们设为静态 - C#

javascript - Javascript中的变量声明方法