c++代码,#include using namespace std; //声明class Point;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

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/27 20:01:44
c++代码,#include using namespace std; //声明class Point;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

c++代码,#include using namespace std; //声明class Point;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
c++代码,
#include
using namespace std;
//声明
class Point;
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

c++代码,#include using namespace std; //声明class Point;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
你的编程习惯有些繁琐和奇怪,共有两点
其一:公有变量最好定义为私有变量,否则就违背了类封装性的初衷了,虽然现在程序没有大的错误,但一旦程序大型化后,那个时候就比较麻烦了
其二:重载运算符函数定义有些繁琐,如
Point operator+( Point &a,Point &b)
{
Point s(a.x+b.x,a.y+b.y);
return s;
}
为何不写成返回一个有参数的构造函数
Point operator+( Point &a,Point &b)
{
return Point(a.x+b.x,a.y+b.y);
}
假如以上的你都接受和吸收的话,那开始看下面我对你题目的详解
运算符重载函数可以是类的成员函数,也可以是类的友元函数,还可以是既非类的成员函数也不是友元函数的普通函数.当然了,最后一个并不常用,原因是无法直接访问类的私有成员.(要访问也可以,只不过会降低程序的效率)
先来说说成员函数重载运算符,当你用其重载时,主函数中c++编译系统将表达式c=a+b解释为a.operator+(b)
所以,将你的程序改成
Point operator+(Point &b)
{
return Point(x+b.x,y+b.y);
}
就可以了
但是这就限制运算符左侧的值必须是一个类对象,不灵活不方便,因此就诞生了友元函数重载运算符
那现在来说说友元函数,当你用其重载时,主函数中c++编译系统将表达式c=a+b解释为operator+(a,b)
Point operator+( Point &a,Point &b)
{
return Point (a.x+b.x,a.y+b.y);
}
当然了,你这样定义只能重载两个类的加,若你想让一个类与整型相加,你可以如下重载
Point operator+( Point &a,int &b)
{
return Point (a.x+b,a.y);
}
注意:加法的交换律在c++中并不适用,也就是说整型与一个类加上述函数是无法完成的.
假如你还不懂的话,额,那你就死记吧,成员函数重载前一个类参数省略,而友元函数重载所有参与运算的参数必须全写出来,而且位置和参数类型要一一对应.
Ps:友元函数的使用会破坏类的封装性,因此原则上说,要尽量将运算符作为成员函数.但考虑到给方面的因素,一般将单目运算符重载为成员函数,将双目运算符重载为友元函数