[問題] undefined reference to static member

看板C_and_CPP (C/C++)作者 (tennishot)時間13年前 (2013/02/03 13:51), 編輯推噓0(007)
留言7則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Dev c++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 請教一下 記得以前上課老師說過如果把class裡面的member設成static 它在這個class之間值會一直存在 如果在任何一個該class的物件裡面改這個值 則其他同class的物件裡面的該member一樣會改 因此可以作為該class object的counter 但是今天我想說試一下static member的用法,於是寫了以下小段程式碼 但卻出現"undesired reference to 'Test::number'"這樣的Linker error 請問是哪裡錯誤呢?謝謝 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) #include <iostream> using namespace std; class Test{ public: Test(){ number = 0; } static int number; }; int main(){ Test* t = new Test[ 3 ]; t[ 0 ].number = 1; cout << "t[2].number = " << t[2].number << endl; t[ 1 ].number++; cout << "t[2].number = " << t[2].number << endl; system("pause"); return 0; } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.251.152.67

02/03 14:02, , 1F
Test::number = 0
02/03 14:02, 1F

02/03 14:05, , 2F
請問是要在外面初始化的意思嗎?
02/03 14:05, 2F

02/03 14:15, , 3F
在class外初始化,int Test::number = 0
02/03 14:15, 3F

02/03 14:17, , 4F
在constructor裡面給static member 值的用意是?
02/03 14:17, 4F

02/03 17:57, , 5F
一定要在宣告外面某處親自初始化它,你這樣它每new一次就會
02/03 17:57, 5F

02/03 17:58, , 6F
初始化一次。
02/03 17:58, 6F

02/03 20:10, , 7F
文章代碼(AID): #1H3VhpwB (C_and_CPP)
文章代碼(AID): #1H3VhpwB (C_and_CPP)