WHCSRL 技术网

C++重载的例子

此处代码,请思考理解

  • 重载运算符,为什么需要返回引用?
  • 什么是委托构造函数?
  • 什么是类内重载,什么是类外重载?默认调用那个?
  • 数组对象
  • 函数对象(仿函数)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
using namespace std;

class Point {
public:
    Point();
    Point(int x, int y);
    //类内重载
    Point operator+(const Point &);
    Point &operator+=(int);
    int operator[](string);
    int getX() {return x; }
    int getY() {return y; }

private:
    friend Point operator+(const Point &, const Point &);
    friend ostream &operator<<(ostream &, const Point &);
    int x, y;
};

class PPoint {
public:
    PPoint(Point *p) : p(p) {}
    Point *operator->() {return p;}
private:
    Point *p;
};

class ADD {
public:
    ADD(int c) : c(c) {}
    int operator()(int a, int b) {
        return a + b + c;
    } 
private:
    int c;
};

//委托构造函数
Point::Point() : Point(0, 0) {}
Point::Point(int x, int y) : x(x), y(y) {}
//数组对象
int Point::operator[](string s) {
    if (s == "x") return x;
    if (s == "y") return y;
    return 0;
}

ostream &operator<<(ostream &out, const Point &a) {
    out << "(" << a.x << "," << a.y << ")";
    return out;
}

Point &Point::operator+=(int n){
    x += n, y += n;
    return *this;
}
//类内重载
Point Point::operator+(const Point &a) {
    cout << "inner operator+" << endl;
    Point c(x + a.x, y + a.y);
    return c;
}
//类外重载
Point operator+(const Point &a, const Point &b) {
    cout << "outer operator+" << endl;
    Point c(a.x + b.x, a.y + b.y);
    return c;
}

int main() {
    ADD add(5);//仿函数,可调用对象
    cout << add(6, 7) << endl;
    Point a(3, 4);
    Point b(7, 9);
    cout << a["x"] << endl;//数组对象
    cout << a["y"] << endl;
    Point c = a + b;
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    (a += 3) += 2;//x和y统一加上3,再加上2
    cout << a << endl;

    PPoint p = &a;
    cout << p->getX() << " " << p->getY() << endl;
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98

输出

18
3
4
inner operator+
(3,4)
(7,9)
(10,13)
(8,9)
8 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
推荐阅读