类模板中使用静态成员(P342)
/*
类模板中允许有静态成员。实际上,定义的静态成员是类模板实例化后的类的静态成员。也就是说,对于一个类模板的每一个实例化类,其所有的对象共享其静态成员。
*/
#include<iostream>
using namespace std;
template<typename T>
class Test
{
public:
Test(T num)
{
k+=num;
}
Test()
{
k+=1;
}
static void incrementK()
{
k+=1;
}
static T k;
};
template<typename T>
T Test<T>::k=0;
int main()
{
//static Field
Test<int>a;
Test<double>b(4);
cout<<"Test<int>::\tk="<<a.k<<endl;
cout<<"Test<double>::\tk="<<b.k<<endl;
Test<int>v;
Test<double>m;
cout<<"Test<int>::\tk="<<Test<int>::k<<endl;
cout<<"Test<double>::\tk="<<Test<double>::k<<endl;
//static Function
cout<<endl;
Test<int>::incrementK();
cout<<"调用 Test<int>::incrementK() Test<int>::k="<<Test<int>::k<<endl;
Test<double>::incrementK();
cout<<"调用 Test<double>::incrementK() Test<double>::k="<<Test<double>::k<<endl;
return 0;
}

浙公网安备 33010602011771号