某些情況下,在寫C++類的時候,希望能通過一個靜態初始化函數來對類的一些靜態成員進行初始化。比如,往靜態的std::map成員或者std::vector成員裡添加一些固定的內容等。這在Java裡通過static塊很容易實現。但在C++裡該怎麼辦呢?
如果要初始化一個普通的靜態成員,只需要在實現檔案(源檔案)中定義該成員並賦予初始值即可,比如:
class Test1 {
public:
static string emptyString;
};
string Test1::emptyString = "";
// also can be
// string Test1::emptyString;
// string Test1::emptyString("");
靜態函數是不能像這樣直接調用的。但是,不妨利用一下C++初始化普通成員的特點來調用靜態初始化函數。當然,這需要定義一個額外的靜態成員變數來輔助一下。如:
class Test2 {
public:
static
vector<string> stringList;
private:
static bool __init;
static bool init() {
stringList.push_back("string1");
stringList.push_back("string2");
stringList.push_back("string3");
return true;
}
};
vector<string> Test2::stringList;
bool Test2::__init = Test2::init();
上面這個樣本中初始化成靜態成員__init的時候就“順便”調用了靜態初始化函數init(),達到預期目的。
項目例子:
#include "StdAfx.h"
#include "CTrackView.h"
#include "DataBaseInfo.h"
CVSS_Rect CTrackView::m_WorldRt(0,0,0,0);
CRect CTrackView::m_ScreenRt(0,0,0,0);
HDC CTrackView::m_HDC = NULL;
v_VnoPoint CTrackView::v_VnoPt;
CTrackView::CTrackView(void)
{
}
CTrackView::~CTrackView(void)
{
}
.......