static 变量只在具体类中共享,不是所有类都共享。
- 定义模板类
template<class T>
class StaticClass
{
public:
StaticClass();
static int m_age;
};
- 实现模板类
#include "StaticClass.h"
template<class T>
StaticClass<T>::StaticClass()
{
}
template<class T> int StaticClass<T>::m_age = 1;
- 调用模板类
#include "StaticClass.cpp"
StaticClass<int> sc1, sc2;
StaticClass<char> sc11, sc22;
sc1.m_age = 10;
sc11.m_age = 100;
cout << "sc1.m_age = "<<sc1.m_age << " sc2.m_age = "<< sc2.m_age <<endl;
cout << "sc11.m_age = "<<sc11.m_age << " sc22.m_age = "<< sc22.m_age <<endl;
- 运行结果