2011-07-16 64 views
0

我得到這個錯誤,我不知道這意味着什麼:未定義的引用靜態變量Foo :: a?

$ mingw32-g++ Test.cpp -o Test.exe 
C:\Documents and Settings\BDL\ccksiYhI.o:Test.cpp:(.text+0x11): undefined reference to 'Foo::a' 
collect2: ld returned 1 exit status 

這是我的代碼。

Test.cpp的

#include <vector> 
#include "Test.h" 

int main() { 
    Foo::a.clear(); 
    return 0; 
} 

Test.h

#include <vector> 
class Foo { 
public: 
    static std::vector<int> a; 
}; 

這不是我的原代碼,但我已經熬下來到這個問題。我是新來的C + +,如果任何人都可以解釋爲什麼這是錯的,我怎麼能解決它,我將不勝感激。

回答

3

您仍然需要定義成員變量,即使它是靜態的。改變你的Test.cpp爲:

#include <vector> 
#include "Test.h" 

std::vector<int> Foo::a; // <-- definition 

int 
main() { 
    Foo::a.clear(); 
    return 0; 
} 
+0

「你需要定義一個類的變量,如果它是靜態的」會更合適。 – Ajay

1

您需要定義靜態成員以及一個翻譯單元,例如,在Test.cpp

std::vector<int> Foo::a; 
1

靜態成員必須在課堂外定義。裏面有一個聲明。

有很多在線網站的例子。搜索「定義C++靜態成員」。

祝你好運,歡迎來到SO。