靜態成員變數的初始化,vector類型變數初始化

來源:互聯網
上載者:User

 某些情況下,在寫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)
{
}

.......

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.