【发布时间】:2020-08-03 02:46:48
【问题描述】:
我有这段 C++ 代码来重载前置增量和后置增量运算符。 这些方法之间的唯一区别是它们的参数数量。
我想知道 C++ 如何理解在运行 y=++x 和 z=x++ 命令时应该调用哪个方法(前增量或后增量)。
class location {
private: int longitude, latitude;
public:
location(int lg = 0, int lt = 0) { longitude = lg; latitude = lt; }
void show() { cout << longitude << "," << latitude << endl; }
location operator++(); // pre-increment
location operator++(int); // post-increment
};
// pre-increment
location location::operator++() { // z = ++x;
longitude++;
latitude++;
return *this;
}
// post-increment
location location::operator++(int) { // z = x++;
location temp = *this;
longitude++;
latitude++;
return temp;
}
int main() {
location x(10, 20), y, z;
cout << "x = ";
x.show();
++x;
cout << "(++x) -> x = ";
x.show();
y = ++x;
cout << "(y = ++x) -> y = ";
y.show();
cout << "(y = ++x) -> x = ";
x.show();
z = x++;
cout << "(z = x++) -> z = ";
z.show();
cout << "(z = x++) -> x = ";
x.show();
}
【问题讨论】: