#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;
}
友元函数重载+运算符
最新推荐文章于 2024-09-28 21:57:37 发布