首页 > 解决方案 > 如何区分 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++operator-overloading

解决方案


本质上缺少 ++ 重载中的参数告诉 c++ 您正在创建前缀重载。

包含参数告诉 c++ 您正在重载后缀运算符。因此,当您运行 ++x 时,它将运行前缀,而 x++ 将运行后缀。

我还可以补充一点,参数中的 int 不是整数数据类型。

如果您想了解更多,那么这就是我找到信息的地方:https ://www.programiz.com/cpp-programming/increment-decrement-operator-overloading


推荐阅读