#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;}
如果觉得《友元函数重载+运算符》对你有帮助,请点赞、收藏,并留下你的观点哦!