C++ 点类重载运算符实现详解
#include
class Point { private: double x, y; public: Point(double a = 0, double b = 0) : x(a), y(b) {} Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); } Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); } bool operator==(const Point& p) const { return x == p.x && y == p.y; } bool operator!=(const Point& p) const { return !(*this == p); } Point& operator++() { x++; y++; return *this; } Point operator++(int) { Point temp(*this); ++(*this); return temp; } Point& operator--() { x--; y--; return *this; } Point operator--(int) { Point temp(*this); --(*this); return temp; } friend istream& operator>>(istream& in, Point& p) { in >> p.x >> p.y; return in; } friend ostream& operator<<(ostream& out, const Point& p) { out << '(' << p.x << ', ' << p.y << ')'; return out; } };
int main() { Point p1(1, 2), p2(3, 4); cout << 'p1 = ' << p1 << endl; cout << 'p2 = ' << p2 << endl; cout << 'p1 + p2 = ' << p1 + p2 << endl; cout << 'p1 - p2 = ' << p1 - p2 << endl; cout << 'p1 == p2? ' << (p1 == p2) << endl; cout << 'p1 != p2? ' << (p1 != p2) << endl; cout << '++p1 = ' << ++p1 << endl; cout << 'p1++ = ' << p1++ << endl; cout << 'p1 = ' << p1 << endl; cout << '--p2 = ' << --p2 << endl; cout << 'p2-- = ' << p2-- << endl; cout << 'p2 = ' << p2 << endl; cout << '请输入一个点的坐标:'; cin >> p1; cout << '你输入的点是:' << p1 << endl; return 0; }
原文地址: https://www.cveoy.top/t/topic/nQTe 著作权归作者所有。请勿转载和采集!