类模板中的static关键字

类模板中static关键字所定义的静态变量,因为编译两次的原理,不同类型的类所使用的静态变量不同,各用各的。

程序:

#include<iostream>
using namespace std;


template<typename T>
class AA
{
public:
    static T m_a;
};
template<typename T>
T AA<T>::m_a = 0;



int main()
{

    AA<int> a1, a2, a3;
    a1.m_a = 10;
    a2.m_a ++;
    a3.m_a ++;
    cout << AA<int>::m_a << endl;
    AA<char> b1, b2, b3;
    b1.m_a = 'a';
    b2.m_a++;
    b3.m_a++;
    cout << AA<char>::m_a << endl;
    //m_a应该是每一种类型的类使用自己的m_a。
    system("pause");
    return 0;
}

运行结果:

原文地址:https://www.cnblogs.com/ymj11/p/13746515.html