复数类模板

template <typename T>
class Complex{
public:
	Complex(T a, T b){
		this->a = a;
		this->b = b;
	}
	void print(){
		cout << "Complex a: " << a << " b: " << b << endl;
	}
	Complex operator+(Complex &c){
		Complex temp(a + c.a, b + c.b);
		return temp;
	}
	//friend ostream& operator << (ostream& out, Complex c);
	//friend istream& operator>> (istream& in, Complex& c);

	//这样依然满足模板化
	friend ostream & operator << (ostream& out, Complex c){
		out << "complex a: " << c.a << " b: " << c.b;
		return out;
	}
	friend istream & operator>> (istream& in, Complex &c){
		cout << "enter a:";
		in >> c.a;
		cout << "enter b:";
		in >> c.b;
		return in;
	}
protected:
private:
	T a;
	T b;
};
//运算符重载的正规写法:重载<< >>只能用友元函数,其他的运算符都要写成成员函数 避免打破封装性
//写在类内部 否则失去模板作用 必须强制说明类型
//ostream & operator << (ostream& out, Complex<int> c){
	//	out << "complex a: " << c.a << " b: " << c.b ;
	//	return out;
//}
//istream & operator>> (istream& in, Complex<int> &c){
	//	cout << "enter a:";
	//	in >> c.a;
	//	cout << "enter b:";
	//	in >> c.b;
	//	return in;
//}
Main:
	Complex<int> c1(10, 20);
	Complex<int> c2(15, 25);
	Complex<int> c3 = c1 + c2;
	//c3.print();
	cout << c3 << endl;;
	/*cin >> c3;
	cout << c3 << endl;*/

类模板中的static关键字:

template <typename T>
class Test{
public:
	Test(T a){
		this->m_a = a;
		m_b = 12;
	}
void print(){
	cout << "this is m_a: " << m_a << " this is m_b addr: " << &m_b << endl;;
}
private:
	T m_a;
	static T m_b;
};
template <typename T>
T Test<T>::m_b = 0;
Main:
	Test<int> t1(5);
	Test<double> t2(10.000);
	t1.print(); //this is m_a: 5 this is m_b addr: 00D70358
	t2.print();//this is m_a: 10 this is m_b addr: 00D70320 注意 m_b的地址变了
	//模板类不会共用一份static变量(除非类型一致) 如Test<int>t1(5);Test<int> t2(10.000); 此时m_b地址相同
	//Test<int> t1(5);Test<double> t2(10.000); 此时m_b地址不同
	//原理:c++编译器帮程序员省略了解析和设定类型 如Test<int>t1(5),int Test<int>::m_b = 0;  Test<double> t2(10.000),
	Test<double>::m_b = 0; 即开辟了不同类型的static变量的空间
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值