对 Point 类重载++(自增)、--(自减)运算符
解:
#include <iostream.h> class Point { public: Point& operator++(); Point operator++(int); Point& operator--(); Point operator--(int); Point() { _x = _y = 0; } int x() { return _x; } int y() { return _y; } private: int _x, _y; }; Point& Point::operator++() { _x++; _y++; return *this; } Point Point::operator++(int) { Point temp = *this; ++*this; return temp; } Point& Point::operator--() { _x--; _y--; return *this; } Point Point::operator--(int) { Point temp = *this; --*this; return temp; } void main() { Point A; cout << "A 的值为:" << A.x() << " , " << A.y() << endl; A++; cout << "A 的值为:" << A.x() << " , " << A.y() << endl; ++A; cout << "A 的值为:" << A.x() << " , " << A.y() << endl; A--; cout << "A 的值为:" << A.x() << " , " << A.y() << endl; --A; cout << "A 的值为:" << A.x() << " , " << A.y() << endl; }
程序运行输出:
A 的值为:0 , 0
A 的值为:1 , 1
A 的值为:2 , 2
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
解:
程序运行输出:
A 的值为:0 , 0
A 的值为:1 , 1
A 的值为:2 , 2
A 的值为:1 , 1
A 的值为:0 , 0