友元函数重载+运算符

  • Post author:
  • Post category:其他


#include<iostream>
//#include<vector>
using namespace std;
class Vector
{
	private:
		int a;
		int b;
	public:
		Vector(){}//定义无参构造函数并赋初值为0; 
		Vector(int i,int j)//重载构造函数; 
		{
			a=i;
			b=j;
		}
		friend Vector operator+(Vector t1,Vector t2);//友元函数重载+运算符; 
		/*{
			Vector tempvector;
			tempvector.a=t1.a+t2.a;
			tempvector.b=t1.b+t2.b;
			return tempvector;
		}*/
		void display()
		{
			cout<<"("<<a<<","<<b<<")"<<endl;
		}
};
Vector operator+(Vector t1,Vector t2)//在类外定义友元函数,重载之后原来的功能保存,只是增加了一个新功能; 
		{
			Vector tempvector;
			tempvector.a=t1.a+t2.a;
			tempvector.b=t1.b+t2.b;
			return tempvector;
		}
int main()
{
	Vector t1(1,2);
	Vector t2(3,4);
	Vector t3;
	cout<<"t1=";
	t1.display();
	cout<<"t2=";
	t2.display();
	t3=t1+t2;
	cout<<"t1+t2=";
	t3.display();
	return 0;
}



版权声明:本文为qq_41404557原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。