运算符本质上是一个特殊的函数,因此也支持像函数一样的重载机制。
并且支持同名函数通过传入参数重载。
代码清单7.1 重载+运算符
#include <iostream>#include <string.h>#include <unistd.h>using namespace std;class Point{private:int x;int y;public:Point() {}Point(int x, int y) : x(x), y(y) {}void showinfo(void){cout<< "x =" << this->x << "y = " << this->y <<endl;}friend Point operator+(Point &p1, Point &p2);};Point operator+(Point &p1, Point &p2){cout << "Point operator+(Point &p1, Point &p2)" << endl;Point n;n.x = p1.x + p2.x;n.y = p1.y + p2.y;return n;}int main(int argc, char **argv){Point p1(1, 2);Point p2(2, 3);Point sum = p1 + p2;sum.showinfo();return 0;}
运行结果为:
x =3 y = 5
代码清单7.2 重载++运算符
首先在类中增加两个友元重载函数
friend Point operator++(Point &p); // ++p
friend Point operator++(Point &p, int n); //p++
并在外部实现
Point operator++(Point &p)
{
p.x = ++p.x;
p.y = ++p.y;
return p;
}
Point operator++(Point &p, int n)
{
Point ret;
ret.x = p.x + n;
ret.y = p.y + n;
return ret;
}
Main函数调用
int main(int argc, char **argv)
{
Point p1(1, 2);
//Point p2(2, 3);
Point sum = operator++(p1);
sum.showinfo();
Point sum2 = operator++(p1,2);
sum2.showinfo();
return 0;
}
运行结果:
x =2 y = 3 x =4 y = 5
代码清单7.3 类内重载
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Point
{
private:
int x;
int y;
public:
Point() {}
Point(int x, int y) : x(x), y(y) {}
void showinfo(void)
{
cout << "x =" << this->x << " "
<< "y = " << this->y << endl;
}
Point operator+(Point &p1);
Point operator++(void); // ++p
Point operator++(int n); //p++
};
Point Point::operator+(Point &p1)
{
cout << "operator +" << endl;
Point n;
n.x = p1.x + this->x;
n.y = p1.y + this->y;
return n;
}
Point Point::operator++(void)
{
cout << "operator ++p" << endl;
this->x = ++this->x;
this->y = ++this->y;
return *this;
}
Point Point::operator++(int n)
{
cout << "operator p++" << endl;
this->x = this->x++;
this->y = this->y++;
return *this;
}
int main(int argc, char **argv)
{
Point p1(1, 2);
Point p2(3, 4);
Point sum = p1+p2;
sum.showinfo();
Point sum2 = ++p1;
sum2.showinfo();
Point sum3 = p1++;
sum2.showinfo();
return 0;
}
运行结果
operator + x =4 y = 6 operator ++ p x =2 y = 3 operator p++ x =2 y = 3\
