首页 > 解决方案 > 如何在 C++ 中为具有 2 个变量的对象重载增量运算符?

问题描述

所以我一直遇到运算符重载的问题。所以我有一个程序,它有一个名为Weight的对象,它有 2 个属性,盎司。我找出了所有其他运算符,但增量一给我带来了麻烦。我试图这样做,但由于某种原因,它不想工作。

以下是头文件中的声明(包括 2 个变量):

    void operator++();
    void operator--();
private:
    int pounds;
    int ounces;

和成员函数:

void Weight::operator++() {
    pounds + 1;
    ounces + 15;
}
void Weight::operator--() {
    pounds - 1;
    ounces - 15;
}

什么都有帮助!

标签: c++operator-overloading

解决方案


发布的代码存在两个问题。

  1. Weight当您增加或减少对象时,不清楚应该发生这种情况。它的价值应该上升/下降一盎司或一磅。

  2. 表达式pounds + 1,ounces + 15等不会改变对象中的任何内容。他们计算一个值,然后丢弃结果。

假设 inrement 运算符将值更改一盎司,您必须使用:

void Weight::operator++() {
    ounces++;

    // If ounces becomes 16, we have to increment pounds by one and set ounces to zero.
    if ( ounces == 16 )
    {
        pounds++;
        ounces = 0;
    }

    // That can also be achieved by using.
    // pounds += (ounces / 16);
    // ounces =  (ounces % 16);
}

此外,重载++运算符的规范做法是返回对对象的引用。因此,您应该使用:

Weight& Weight::operator++() {
    ounces++;

    // If ounces becomes 16, we have to increment pounds by one and set ounces to zero.
    if ( ounces == 16 )
    {
        pounds++;
        ounces = 0;
    }

    // That can also be achieved by using.
    // pounds += (ounces / 16);
    // ounces =  (ounces % 16);

    return *this;
}

您必须operator--类似地更新该功能。


推荐阅读