类模板与static成员

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值