在類定義中定義靜態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。
3 回答

動漫人物
TA貢獻1815條經驗 獲得超10個贊
Bjarne Stroustrup 在他的C ++ FAQ中的例子表明你是正確的,只要你拿到地址就需要一個定義。
class AE { // ...public: static const int c6 = 7; static const int c7 = 31;};const int AE::c7; // definitionint f(){ const int* p1 = &AE::c6; // error: c6 not an lvalue const int* p2 = &AE::c7; // ok // ...}
他說:“如果(并且只有)它具有異類定義,你可以獲取靜態成員的地址”。這表明它會起作用。也許你的min函數會在幕后以某種方式調用地址。
- 3 回答
- 0 關注
- 545 瀏覽
添加回答
舉報
0/150
提交
取消