猿问

在类定义中定义静态const整数成员

在类定义中定义静态const整数成员

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

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

#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。



慕容708150
浏览 526回答 3
3回答

动漫人物

Bjarne Stroustrup&nbsp;在他的C ++ FAQ中的例子表明你是正确的,只要你拿到地址就需要一个定义。class&nbsp;AE&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;...public: &nbsp;&nbsp;&nbsp;&nbsp;static&nbsp;const&nbsp;int&nbsp;c6&nbsp;=&nbsp;7; &nbsp;&nbsp;&nbsp;&nbsp;static&nbsp;const&nbsp;int&nbsp;c7&nbsp;=&nbsp;31;};const&nbsp;int&nbsp;AE::c7;&nbsp;&nbsp;&nbsp;//&nbsp;definitionint&nbsp;f(){ &nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;int*&nbsp;p1&nbsp;=&nbsp;&AE::c6;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;error:&nbsp;c6&nbsp;not&nbsp;an&nbsp;lvalue &nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;int*&nbsp;p2&nbsp;=&nbsp;&AE::c7;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;ok &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;...}他说:“如果(并且只有)它具有异类定义,你可以获取静态成员的地址”。这表明它会起作用。也许你的min函数会在幕后以某种方式调用地址。

人到中年有点甜

另外,对于整数类型,另一种方法是将常量定义为类中的枚举:class&nbsp;test{public: &nbsp;&nbsp;&nbsp;&nbsp;enum&nbsp;{&nbsp;N&nbsp;=&nbsp;10&nbsp;};};
随时随地看视频慕课网APP
我要回答