静态变量需要在.cpp初始化,否则报错连接错误,
对于原始数据, int, double, …
simple.h
class Simple
{
public:
Simple(void);
~Simple(void);
static int GetInt(void);
private:
static int _i;
};
simple.cpp
int Simple::GetInt(void)
{
return _i;
}
连接出错:
error LNK2001: unresolved external symbol "private: static int Simple::_i" (?_i@Simple@@0HA)
error LNK2001: unresolved external symbol "private: static int Simple::_i" (?_i@Simple@@0HA)
需要在.cpp文件中初始化静态成员变量,初始化跟所在位置无关
int Simple::GetInt(void)
{
return _i;
}
int Simple::_i = 0;
对于数组静态变量,头文件可以如下声明
static int _i[10];
或者不指定对应数组长度
static int _i[].cpp文件可以如下初始化:
int Simple::_i[10] = {0};
对于STL容器静态变量,初始化方法比较复杂,需要借助一个静态构造函数,通过拷贝构造函数来实现初始化
simple.h定义为:
#include <map>
using namespace std;
typedef map<int, int> INT2INT;
class Simple
{
public:
Simple(void);
~Simple(void);
static bool Find(int key);
private:
static INT2INT CreateMap(void);
static INT2INT _i;
};
simple.cpp定义为:
bool Simple::Find(int key)
{
INT2INT::iterator it = _i.find(key);
if (it == _i.end())
return false;
return true;
}
INT2INT Simple::CreateMap(void)
{
INT2INT _tmp;
return _tmp;
}
INT2INT Simple::_i(Simple::CreateMap());