2012-04-08 56 views
3

我不知道這段代碼有什麼問題。我有以下的,很簡單,等級:靜態類成員獲取「未定義參考」。不知道爲什麼

class SetOfCuts{ 
public: 

    static LeptonCuts Leptons; 
    static ElectronCuts TightElectrons; 
    static ElectronCuts LooseElectrons; 
    //*** 
    //more code 
}; 

,例如,類型ElectronCuts在同一個.h文件中之前定義爲:

struct ElectronCuts{ 
    bool Examine; 
    //**** 
    //other irrelevant stuff 
}; 

沒有什麼太複雜了,我想。

我的理解是,在主程序中,我可以這樣做:

SetOfCuts::LooseElectrons.Examine = true; 

,但如果我這樣做,我得到:

undefined reference to `SetOfCuts::LooseElectrons' 

相反,如果我做的:

bool SetOfCuts::LooseElectrons.Examine = true; 

我得到:

error: expected initializer before '.' token 

我不知道爲什麼我不能訪問結構的成員。我錯過了一些關於靜態數據成員的明顯信息,但我不知道它是什麼。

非常感謝。

回答

4

任何靜態引用都必須在特定的源文件(而不僅僅是頭文件)中聲明,因爲鏈接完成後它必須存在某處。

例如,如果你有這樣的在你Foo.h

class SetOfCuts{ 
public: 

    static LeptonCuts Leptons; 
    static ElectronCuts TightElectrons; 
    static ElectronCuts LooseElectrons; 
}; 

然後在Foo.cpp,你將有

#include <Foo.h> 
LeptonCuts SetOfCuts::Leptons = whatever; 
ElectronCuts SetOfCuts::ThighElectrons = whatever; 
.. 

最後,在你的main.cpp中,你將能夠做到

#include <Foo.h> 
SetOfCuts::Leptons = whatever; 
+0

非常感謝您的回覆。它幫助了很多。 – elelias 2012-04-08 18:32:47

3

「未定義參考」錯誤你得到一個鏈接錯誤說你聲明靜態數據成員,但你有沒有真正定義他們的任何地方。在C++中,使用靜態變量有兩個步驟 - 首先在類中指定它,就像你已經完成的那樣,然後必須在某處放置一個定義。這與您在頭文件中定義函數的方式類似 - 您在頭文件中創建函數原型,然後在源文件中提供實現。

在你的情況下,你已經實現了成員函數SetOfCuts在源文件中,加入下面幾行:

LeptonCuts SetOfCuts::Leptons; 
ElectronCuts SetOfCuts::TightElectrons; 
ElectronCuts SetOfCuts:LooseElectrons; 

這說明在什麼翻譯單元實際上是定義的靜態成員C++。如果你願意,你也可以在這裏指定構造函數參數。請注意,你在不是這裏重複static這個關鍵字。

希望這會有所幫助!

+0

非常感謝!,它確實有幫助。很多 – elelias 2012-04-08 18:32:30

相關問題