下面程序中对一维坐标点类Point进行运算符重载
#include <iostream> using namespace std; class Point { public: Point(int val) {x=val;} Point & operator++() {x++; return *this; } Point operator++(int) {Point old = *this; ++(*this); return old;} int GetX() const {return x;} private: int x; }; int main() { Point a(10); cout << (++a).GetX(); cout << a++.GetX(); return 0; }
编译和运行情况是()。
A.运行时输出1011
B.运行时输出1111
C.运行时输出1112
D.编译有错
参考答案:B
解析:
本题考查的知识点是:重载增1运算符“++”。++既可以是前缀运算符(前增1),又可以是后缀运算符(后增1)。为了区分这两种情况,重载这两个运算符时必须在格式上有所区别:重载后缀++时必须多一个虚拟参数:int。在本题中,Point& operator++()重载的是前缀形式,而Point operator++(int)则是后缀形式。所以,主函数中第1条输出语句cout<<(++a).GetX();等价于cout<<a.operator++().GetX();,即输出 11,此时a.x的值为11。而第2条输出语句cout<<a++.GetX();等价于cout<< a.operator++(0).GetX();(式中的0可以是任意整数),在这个后缀++的重载函数中,首先创建了一个Point对象old保存自身(*this),然后通过语句++(*this];调用前缀++的重载函数,此时自身虽然已经改变,但它返回的是改变前保存的old对象,因此还是输出11。故本题应该选择B。