我的理解是 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 ofconst
integral orconst
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/