[英]Proper usage of static class members
擁有靜態類成員的正確方法是什么?
我試圖創建一個度量標准類,以便可以在所有文件中包含“ metrics.h”,並使用其中的某些變量(靜態變量)來跟蹤多個單獨編譯的庫中的時序信息。
這些庫中的一個是所有其他庫所共有的,因此當我使用metrics.h對其進行編譯時,它可以很好地編譯,但是當我嘗試編譯使用通用的其他庫之一時,將得到“多個定義”。錯誤以及一些未定義的引用。
這個通用指標類應該是什么樣? 我不想將其實例化為用戶變量,我只想使用類似
Metrics :: startTime = ....
和Metrics :: calcTime =...。
在公共庫或鏈接到公共庫的其他一個庫中
與其定義多個靜態成員,不如將它們全部打包為一個靜態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
,並且為所有后續調用返回了相同的對象。
在頭文件中:
class Metrics {
public:
static int startTime ;
} ;
在一個 cpp
文件中:
int Metrics::startTime ;
// metrics.hpp
class metrics {
static int i; // declaration
};
// metrics.cpp
int metrics::i(0); // definition
除此之外,所有這些都是構造函數的正確實現
您不應以相同的代碼最終被鏈接到一個程序中多次的方式來組合庫。 將度量標准類以及應該與之一起包裝的所有其他類隔離在一個庫中(有關指導,請參見Robert Martin發布的六種包裝原則)。 將依賴於它的其他類放在其他庫中(或者,如果那些包裝原則表明它們屬於同一類,則將它們全部放在一個庫中)。 鏈接程序時,請鏈接所需的所有庫,包括依賴於度量標准類的庫和包含度量標准類的(一個)庫。
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
Metrics.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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.