// operator和&operator !
#include <iostream>
using namespace std;
//声明
class Point;
Point operator-(Point &a,Point &b);
Point &operator+(Point &a,Point &b);
//定义点类
class Point
{
public:
int x,y;
char name;
Point(){}
Point(char n1,int xx,int yy){name=n1;x=xx;y=yy;}
void print(){ cout<<name<<"=("<<x<<","<<y<<")\n"; }
friend Point operator-(Point &a,Point &b);
friend Point &operator+(Point &a,Point &b);
};
//重载-号操作(返回值)
Point operator-( Point &a,Point &b)
{
Point s('s',a.x-b.x,a.y-b.y);
return s;
}
//重载+号操作(返引用)
Point &operator+( Point &a,Point &b)
{
a.x+=b.x;
a.y+=b.y;
return a;
}
//主函数
int main()
{
Point a('a',3,20),b('b',1,5),c('c',10,15);
a.print();
b.print();
c=a-b;
c.print();
a.print();
b.print();
c=a+b;
c.print() ;
cout<<"没有& 返回的是值,有&返回的是引用"<<endl;
return 0;
}
//没有& 返回的是值,有&返回的是引用
//运行结果如下,自己研究一下,就会明白!
/*
a=(3,20)
b=(1,5)
s=(2,15)
a=(3,20)
b=(1,5)
a=(4,25)
没有& 返回的是值,有&返回的是引用
*/
operator和&operator
最新推荐文章于 2023-11-01 17:33:07 发布