2011-04-08 47 views
0

有靜態類成員的正確方法是什麼?正確使用靜態類成員

我正在嘗試創建一個度量類,以便我可以在所有文件中包含「metrics.h」,並使用它的某些變量(靜態變量)跟蹤跨多個單獨編譯的庫的時間信息。

這些庫中的一個對所有其他庫都是通用的,所以當我編譯它時,使用metrics.h,它編譯得很好,但是當我試圖編譯其中一個使用common的附加庫時,我得到「多重定義」錯誤,以及一些未定義的參考。

這個常見的指標類應該是什麼樣的?我不希望有它實例化用戶變量,我只是想使用類似

指標:: STARTTIME = ....

和度量:: calcTime = ....

無論是在公共庫,或鏈接到共同

回答

1

在頭文件西奧療法庫之一:

class Metrics { 
    public: 
    static int startTime ; 
    } ; 

正好一個cpp文件:

int Metrics::startTime ; 
+0

我可以使用度量::開始時間超過一個CPP文件? – Derek 2011-04-08 17:57:07

+1

是的,但聲明('int Metrics :: startTime;')只能出現在一個文件中。 – TonyK 2011-04-08 18:01:34

1
// metrics.hpp 
class metrics { 
static int i; // declaration 
}; 

// metrics.cpp 
int metrics::i(0); // definition 

除此之外,它是所有正確實施構造的

+0

構造函數與它有什麼關係? – TonyK 2011-04-08 18:02:22

+0

在程序啓動時,如果功能/資源可能受限制/不可用,您必須初始化一次可能複雜的類型。所以你必須保證正確的初始化。還有其他方法來聲明共享數據......但它們每個都有問題。最好避免靜態數據,並儘可能延遲其需求,或者作爲另一個實例的依賴項(變量)。 – justin 2011-04-08 18:23:46

1

你不應該以這樣的方式,同樣的代碼最終得到鏈接到程序超過組合庫一旦。在一個庫中隔離您的度量類,以及應該打包的任何其他類(請參閱Robert Martin公佈的六個包裝原則以獲得指導)。將其他依賴於它的類放在其他庫中(或者如果這些包裝原理顯示它們屬於同一個庫,則將它們全部放入一個庫中)。鏈接程序時,鏈接所有需要的庫,包括依賴於度量標準類的庫和包含度量標準類的(一個)庫。

2

而不是定義一些靜態成員,它可能會更好地將它們全部打包到一個靜態struct成員。

甚至比直接實例化和訪問此靜態成員更好的隱藏它在一個getter函數內。

class metrics { 
    ... 
    struct measurements { // struct may be private; you can still access 
     double startTime; // the members of the result of the getter fn. 
     double calcTime; 
     ... 
    }; 

public: 
    static measurements &getMeasurements() { 
     static measurements instance; 
     return instance; 
    } 
}; 

有了這個,你不需要添加任何東西到.cpp文件。在調用getMeasurements時第一次創建了measurements對象instance,並且所有後續調用都返回相同的對象。

+0

+1爲本地靜態成語! – 2011-04-08 18:08:11

+0

恕我直言,這個問題只有一個正確的答案... – Potatoswatter 2011-04-08 18:25:52

+0

我同意 - >不使用全局變量:) – 2011-04-08 18:27:37

0

Metrics.h

#ifndef _METRICS_H 
#define _METRICS_H 

class Metrics { 
    ... 
    public: 
     Metrics(); 
     //declare the static variables in the header for the class 
     static int startTime; 
     static int calcTime; 
} 

#endif 

指標。CPP

#include "Metrics.h" 

Metrics::Metrics(){ 
    ... 
} 

//define and initialize the variables in the implementation of the class 
int Metrics::startTime = 15; 
int Metrics::calcTime = 20; 

的main.cpp

#include "Metrics.h" 

int main(){ 
    //use the static variables elsewhere 
    int a = Metrics::startTime; 
}