如何在C ++中为具有2个变量的Object重载增量运算符?

问题描述 投票:1回答:1

所以我一直遇到运营商重载问题。所以我有一个程序,它有一个名为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个回答
1
投票

发布的代码有两个问题。

  1. 当你增加或减少Weight对象时,不清楚这应该发生。它的价值应该上涨/下跌一盎司还是一磅。
  2. 表达式qazxsw poi,qazxsw poi等不会改变对象中的任何内容。他们计算一个值,结果被丢弃。

假设增量运算符将值更改为1盎司,则必须使用:

pounds + 1

此外,重载qazxsw poi运算符的规范实践是返回对象的引用。因此,你应该使用:

ounces + 15

你必须类似地更新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); } 功能。

© www.soinside.com 2019 - 2024. All rights reserved.