C++ 模板类中的static变量和函数 初始化

关键词: 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>();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值