在类定义中定义静态const整数成员 [英] Defining static const integer members in class definition
问题描述
我的理解是,C ++允许静态const成员被定义在类中,只要它是一个整数类型。
My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.
为什么,我有链接器错误?
Why, then, does the following code give me a linker error?
#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的调用,代码编译和链接很好:
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?
编译器是Linux上的gcc 4.4。
My compiler is gcc 4.4 on Linux.
推荐答案
我理解C ++允许在类中定义静态const成员只要它是一个整数类型。
你是一个正确的。您可以在类声明中初始化静态const积分,但这不是一个定义。
You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.
有趣的是,如果我注释掉调用std :: min,代码编译和链接很好(即使test :: N也引用了上一行)。
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).
任何想法?
std :: min通过const引用获取其参数。
std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition.
这里是第/节:
9.4.2 / 4 - 如果 static
数据成员是 const
integer或 const
枚举类型,它在类定义中的声明可以指定一个常量初始化器常数表达式(5.19)。在这种情况下,成员可以出现在整数常数表达式中。如果成员在程序中使用,并且命名空间范围定义不包含 initializer ,那么该成员仍然在命名空间范围中定义。
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.
看看楚的答案可能的解决方法。
See Chu's answer for a possible workaround.
这篇关于在类定义中定义静态const整数成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!