栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

复数类模板

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

复数类模板

template 
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 c){
	//	out << "complex a: " << c.a << " b: " << c.b ;
	//	return out;
//}
//istream & operator>> (istream& in, Complex &c){
	//	cout << "enter a:";
	//	in >> c.a;
	//	cout << "enter b:";
	//	in >> c.b;
	//	return in;
//}
Main:
	Complex c1(10, 20);
	Complex c2(15, 25);
	Complex c3 = c1 + c2;
	//c3.print();
	cout << c3 << endl;;
	

类模板中的static关键字:

template 
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 
T Test::m_b = 0;
Main:
	Test t1(5);
	Test 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变量(除非类型一致) 如Testt1(5);Test t2(10.000); 此时m_b地址相同
	//Test t1(5);Test t2(10.000); 此时m_b地址不同
	//原理:c++编译器帮程序员省略了解析和设定类型 如Testt1(5),int Test::m_b = 0;  Test t2(10.000),
	Test::m_b = 0; 即开辟了不同类型的static变量的空间
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/994334.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号