题目:
定义Point类,有坐标x,y两个成员变量,利用成员函数对Point类重载“++”运算符,实现对坐标值的改变。具体要求如下:
(1) 编写程序定义Point类,在类中定义整型的私有成员变量x,y;
(2) 定义成员函数Point& operator++(); Point operator++(int);以实现对Point类重载“++”运算符,分别重载前置++和后置++;
(3) 编写主函数测试。
参考:
#include <iostream> using namespace std; class Point { private: double x; double y; public: Point(double X = 0, double Y = 0) :x(X), y(Y) {} Point operator++(); Point operator++(int); void print(); }; Point Point::operator++() { ++x; ++y; return *this; } Point Point::operator++(int) { Point P = *this; x++; y++; return P; } void Point::print() { cout << "(" << x << "," << y << ")" << endl; } int main(void) { Point t1(1, 1); t1.print(); t1++; t1.print(); Point t2 = t1++; t2.print();
}
|
图片版:
