先看一个简单的
class Point{
public:
int x;
int y;
public:
Point(int x = 0, int y = 0){
this->x = x;
this->y = y;
}
void myprint(){
cout << x << "," << y << endl;
}
};
//重载+号
Point operator+(Point &p1, Point &p2){
Point tmp(p1.x + p2.x, p1.y + p2.y);
return tmp;
}
//重载-号
Point operator-(Point &p1, Point &p2){
Point tmp(p1.x - p2.x, p1.y - p2.y);
return tmp;
}
void main(){
Point p1(10,20);
Point p2(20,10);
Point p3 = p1 + p2;
p3.myprint();
system("pause");
}
如上,按这个套路重新写运算符就行了,这个例子是在类的外部定义的,一般来说,是在类内部定义,如下:、
class Point{
public:
int x;
int y;
public:
Point(int x = 0, int y = 0){
this->x = x;
this->y = y;
}
//成员函数,运算符重载
Point operator+(Point &p2){
Point tmp(this->x + p2.x, this->y + p2.y);
return tmp;
}
void myprint(){
cout << x << "," << y << endl;
}
};
void main(){
Point p1(10, 20);
Point p2(20, 10);
//运算符的重载,本质还是函数调用
//p1.operator+(p2)
Point p3 = p1 + p2;
p3.myprint();
system("pause");
}
这样写就是在类的内部定义
但是,但类的成员变量是private时,这样写就不行了,就必须要用友元函数来解决这个重定义的问题:
class Point{
friend Point operator+(Point &p1, Point &p2);
private:
int x;
int y;
public:
Point(int x = 0, int y = 0){
this->x = x;
this->y = y;
}
void myprint(){
cout << x << "," << y << endl;
}
};
Point operator+(Point &p1, Point &p2){
Point tmp(p1.x + p2.x, p1.y + p2.y);
return tmp;
}
void main(){
Point p1(10, 20);
Point p2(20, 10);
//运算符的重载,本质还是函数调用
//p1.operator+(p2)
Point p3 = p1 + p2;
p3.myprint();
system("pause");
}
这样就解决了~