1.从类模板实例化的每个模板类都有自己的类模板数据成员,该模板类的所有对象共享一个static数据成员
2.和非模板类的static数据成员一样,模板类的static数据成员也应该在文件范围定义和初始化
3.每个模板类有自己的类模板的static数据成员副本
#include<iostream>
const double pi = 3.14159;
using namespace std;
template<typename T>
class Circle//定义一个类模板
{
T radius;
static int total;//类模板的静态数据成员(不受public,private之类的影响)
public:
Circle(T r = 0)
{
radius = r;
total++;
}
void Set_Radius(T r)
{
radius = r;
}
double Get_Radius()
{
return radius;
}
double Get_Girth()
{
return 2 * pi*radius;
}
double Get_Area()
{
return pi*radius*radius;
}
static int showTotal();//类模板的静态成员函数
};
template<typename T>
int Circle<T>::total = 0;//静态成员必须初始化
//类模板的定义
template<typename T>
int Circle<T>::showTotal()
{
return total;
}
int main()
{
Circle<int >A, B;//创建2个对象
A.Set_Radius(16);
cout << "A的半径为=" << A.Get_Radius() << endl;
cout << "A的周长为=" << A.Get_Girth() << endl;
cout << "A的面积=" << A.Get_Area() << endl;
B.Set_Radius(105);
cout << "B的半径为=" << B.Get_Radius() << endl;
cout << "B的周长为=" << B.Get_Girth() << endl;
cout << "B的面积=" << B.Get_Area() << endl;
cout << "Total1=" << Circle<int>::showTotal() << endl;//也可以使用A.ShowTotal()或者B.ShowTotal();
cout << endl;
cout << endl;
Circle<double> X(6.23), Y(10.5), Z(25.6);
cout << "X的半径为" << X.Get_Radius() << endl;
cout << "X的周长为=" << X.Get_Girth() << endl;
cout << "X的面积=" << X.Get_Area() << endl;
cout << "Y的半径为" << Y.Get_Radius() << endl;
cout << "Y的周长为=" << Y.Get_Girth() << endl;
cout << "Y的面积=" << Y.Get_Area() << endl;
cout << "Z的半径为" << Z.Get_Radius() << endl;
cout << "Z的周长为=" << Z.Get_Girth() << endl;
cout << "Z的面积=" << Z.Get_Area() << endl;
cout << "total2=" << Circle<double>::showTotal() << endl;
cin.get();
return 0;
}