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

.......

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
  • 2021-11-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-16
  • 2021-04-12
  • 2021-05-21
  • 2022-12-23
相关资源
相似解决方案