2012-04-22 251 views
1

我在名爲GTAODV的類中創建了一個靜態成員數組。C++中的靜態成員數組

gtaodv/gtaodv.o: In function `GTAODV::command(int, char const* const*)': 
gtaodv.cc:(.text+0xbe): undefined reference to `GTAODV::numdetections' 
gtaodv.cc:(.text+0xcc): undefined reference to `GTAODV::numdetections' 
gtaodv/gtaodv.o: In function `GTAODV::check_malicious(GTAODV_Neighbor*)': 
gtaodv.cc:(.text+0x326c): undefined reference to `GTAODV::numdetections' 
gtaodv.cc:(.text+0x3276): undefined reference to `GTAODV::numdetections' 
collect2: ld returned 1 exit status 

爲什麼會這樣:

static int numdetections[MAXNODES]; 

然而,當我試圖將類的方法(下面的例子)中訪問這個數組,

numdetections[nb->nb_addr]++; 
for(int i=0; i<MAXNODES; i++) if (numdetections[i] != 0) printf("Number of detections of %d = %d\n", i, numdetections[i]); 

鏈接器在編譯過程中給出了一個錯誤發生?

+3

因爲你的鏈接器不知道'numdetections'的定義。你在哪裏使用這個變量,定義在哪裏? – 2012-04-22 16:52:31

+0

我已經在類GTAODV中定義了numdetections,並且我在GTOADV成員函數中使用它。 – vigs1990 2012-04-22 16:53:57

+0

請發佈代碼... – 2012-04-22 16:54:27

回答

10

發生此錯誤時,您很可能忘記定義靜態成員。您的類定義中假設的:

class GTAODV { 
public: 
    static int numdetections[MAXNODES]; // static member deklaration 
    [...] 
}; 

在一個源文件:

int GTAODV::numdetections[] = {0}; // static member definition 

注意在類的聲明之外的定義。

編輯這應該回答關於「爲什麼」的問題:靜態成員可以在沒有具體對象存在的情況下存在,即您可以使用numdetections而不實例化任何對象GTAODV。爲了實現這種外部連接必須是可能的,因此必須存在靜態變量的定義,以供參考:Static data members (C++ only)

+1

您必須將該定義放置在cpp文件中,以便僅定義一次。 – zmccord 2012-04-22 16:58:21

+0

是的,這正是錯誤的原因。你能解釋爲什麼會發生這種情況嗎? - 我認爲內存是在聲明時爲靜態成員數組分配的。我這樣初始化靜態成員值,但我不知道如何初始化一個靜態成員數組。 – vigs1990 2012-04-22 17:03:30

+0

@zmccord感謝提示,作出澄清的編輯。 – 2012-04-22 17:05:30