
3个回答
展开全部
下面是一个+号的重载操作:
#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;
Point(){}
Point(int xx,int yy){x=xx;y=yy;}
void print(){ cout<<"("<<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(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;
}*/
//主函数
void main()
{
Point a(3,2),b(1,5),c;
c=a+b;
c.print();
}
将注释替换过来,就可以得到&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;
Point(){}
Point(int xx,int yy){x=xx;y=yy;}
void print(){ cout<<"("<<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(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;
}*/
//主函数
void main()
{
Point a(3,2),b(1,5),c;
c=a+b;
c.print();
}
将注释替换过来,就可以得到&operator+的重载了
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询