c++ - 如何区分 C++ 中两个相似的运算符重载
问题描述
我有这段 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();
}
解决方案
本质上缺少 ++ 重载中的参数告诉 c++ 您正在创建前缀重载。
包含参数告诉 c++ 您正在重载后缀运算符。因此,当您运行 ++x 时,它将运行前缀,而 x++ 将运行后缀。
我还可以补充一点,参数中的 int 不是整数数据类型。
如果您想了解更多,那么这就是我找到信息的地方:https ://www.programiz.com/cpp-programming/increment-decrement-operator-overloading
推荐阅读
- python - 如何在类方法中就地更改列表元素
- yii2 - 如何在 yii2 gii 生成的 crud 中添加自定义新字段
- python - 具有柱式变压器和管道的 ML 模型的参数调整
- html - 制作按钮使用动画来取消悬停鼠标
- php - PHP session_start() 和 session_abort() 的行为看起来有些出乎意料
- html - 为什么包裹在锚标签中时图像尺寸会缩小?
- javascript - 从 javascript 录制和上传音频
- flutter - 如何在颤动中用平移、倾斜和缩放值填充 Matrix4?
- javascript - 搜索嵌套的对象数组并返回所有匹配项的完整路径
- xcode - 项目构建成功但预览时出现很多错误