运算符本质上是一个特殊的函数,因此也支持像函数一样的重载机制。
并且支持同名函数通过传入参数重载。

代码清单7.1 重载+运算符
  1. #include <iostream>
  2. #include <string.h>
  3. #include <unistd.h>
  4. using namespace std;
  5. class Point
  6. {
  7. private:
  8. int x;
  9. int y;
  10. public:
  11. Point() {}
  12. Point(int x, int y) : x(x), y(y) {}
  13. void showinfo(void)
  14. {
  15. cout<< "x =" << this->x << "y = " << this->y <<endl;
  16. }
  17. friend Point operator+(Point &p1, Point &p2);
  18. };
  19. Point operator+(Point &p1, Point &p2)
  20. {
  21. cout << "Point operator+(Point &p1, Point &p2)" << endl;
  22. Point n;
  23. n.x = p1.x + p2.x;
  24. n.y = p1.y + p2.y;
  25. return n;
  26. }
  27. int main(int argc, char **argv)
  28. {
  29. Point p1(1, 2);
  30. Point p2(2, 3);
  31. Point sum = p1 + p2;
  32. sum.showinfo();
  33. return 0;
  34. }

运行结果为:

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\