我有这段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();
}发布于 2020-08-03 02:56:36
本质上,忽略++重载中的参数会告诉c++您正在创建前缀重载。
包括参数告诉c++您正在重载后缀操作符。因此,当您运行++x时,它将运行前缀,而x++将运行后缀。
此外,我还可以补充一下,参数中的int不是整数数据类型。
如果您想要更多的理解,那么这里就是我找到信息的地方:https://www.programiz.com/cpp-programming/increment-decrement-operator-overloading
https://stackoverflow.com/questions/63223074
复制相似问题