C++重载练习

#include <iostream>
using namespace std;

class Point
{
public:
    explicit Point(int x = 0, int y = 0)
        : x(x), y(y)
        {}
    Point(Point &p) {
        this->x = p.getX();
        this->y = p.getY();
    }
    int getX() const { return x; }
    int getY() const { return y; }

    Point& operator ++ ();
    Point operator ++ (int);
    Point& operator -- ();
    Point operator -- (int);

private:
    int x;
    int y;
};

Point & Point::operator++()
{
    this->x++;
    this->y++;
    return *this;
}

Point Point::operator++(int)
{
    Point old = *this;
    ++(*this);
    return old;
}

Point & Point::operator--()
{
    this->x--;
    this->y--;
    return *this;
}

Point Point::operator--(int)
{
    Point old = *this;
    --(*this);
    return old;
}

int main(int argc, char **argv) 
{
    Point p1(1, 1);
    cout << p1.getX() << "," << p1.getY() << endl;

    Point p2(2, 2);
    p2 = p1++;
    cout << p1.getX() << "," << p1.getY() << endl;
    cout << p2.getX() << "," << p2.getY() << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/YZS_L_H/article/details/63254942