2011-05-31 81 views
0

我有以下的類定義和main()。有人可以指出我爲什麼得到錯誤嗎?靜態變量和函數的用法

/tmp/ccre4um4.o: In function `test::test()': 
test_static.cpp:(.text._ZN4testC1Ev[test::test()]+0x1b): undefined reference to `test::a' 
/tmp/ccre4um4.o: In function `test::send(int)': 
test_static.cpp:(.text._ZN4test4sendEi[test::send(int)]+0x12): undefined reference to `test::a' 
collect2: ld returned 1 exit status 

的錯誤是相同的,即使我用c.send(1),而不是測試::發送(1):

#include <iostream> 
#include <list> 
using namespace std; 

class test 
{ 
protected: 
    static list<int> a; 
public: 
    test() 
    { 
    a.push_back(150); 
    } 
    static void send(int c) 
    { 
    if (c==1) 
     cout<<a.front()<<endl; 
    } 
}; 

int main() 
{ 
    test c; 
    test::send(1); 
    return 0; 
} 

,我得到的是如下的錯誤。先謝謝您的幫助。

回答

6

你已經宣稱test::a,但你沒有定義爲它。在命名空間範圍內添加定義:

list<int> test::a; 
+0

對不起。我不明白。你能否詳細說明一下? – 2011-05-31 21:39:59

+0

@Neel:如果你聲明瞭一個函數'void foo();'但是沒有定義它就調用它會怎麼樣?顯然這樣的事情是行不通的。靜態數據成員也是如此 - 聲明它們是不夠的,它們也必須被定義。我的答案顯示了該定義的語法。 – ildjarn 2011-05-31 21:41:50

+0

謝謝。我知道了。即使經過C++多年的工作,我也從來沒有回憶過爲靜態變量做過這樣的事情。謝謝您的幫助。 – 2011-05-31 21:51:25