自考新教材-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>:: k=" << a.k << endl;
cout << "Test<double>:: k=" << b.k << endl;
Test<int>v;
Test<double>m;
cout << "Test<int>:: k=" << Test<int>::k << endl;
cout << "Test<double>:: k=" << 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;
system("pause");
return 0;
}

运行结果:

原文地址:https://www.cnblogs.com/duanqibo/p/12266611.html