关键词: C++ 模板 static 变量 函数 初始化
这篇文章主要介绍关于模板类中如果有static变量如何初始化问题。
重要:如果不初始化static变量,那么编译可能没有问题,但是程序有问题,可能编译有问题,但是不能确定是初始化问题。
#include"iostream"
class C
{
int ccc;
};
class A
{
public:
A()
{
}
A(const std::string &str)
{
A::stt++;
}
bool flag;
std::string name;
public:
static int stt;
static int &getstt(){return stt;}
static std::map<std::string, bool *> m_mapTopic2Data;
static bool & flahh(const std::string &str){return *(m_mapTopic2Data[str]);}
};
template<class msgtype>
class B :public A
{
public:
B(const std::string &str)
{
A::stt++;
bflag = false;
m_mapTopic2Data[str] = &flag;
}
static std::vector<std::string > topic;
msgtype a;
bool bflag;
void print()
{
std::cout<<"msg"<<a<<std::endl;
}
public:
};
std::map<std::string, bool *> A::m_mapTopic2Data = std::map<std::string, bool *>();
int A::stt=0;
int main(int argc, char *argv[])
{
B<int> b1("b1");
B<int> b2("b2");
B<int> b3("b3");
B<int> b4("b4");
b2.flag = true;
b3.flag = false;
// b4.flag = false;
// B<int>::flahh("b1") = true;
// B<int>::flahh("b2") = false;
// B<int>::flahh("b3") = true;
// B<int>::flahh("b4") = false;
std::cout<<"flag "<< B<int>::flahh("b1") <<" "<<B<int>::flahh("b2") <<" "<<B<int>::flahh("b3") <<" "<<B<int>::flahh("b4")<<" ~"<<std::endl;
std::cout<<"A::stt : "<<A::stt<<std::endl;
return 1;
}
如程序 没有模板的A类中的静态变量初始化
std::map<std::string, bool *> A::m_mapTopic2Data = std::map<std::string, bool *>(); int A::stt=0;
有模板的初始化有两种,一种是需要确定模板到底是啥,一种是不需要确定是啥不需要确定模板类型为
template <typename T> std::vector<std::string> B<T>::topic = std::vector<std::string>();