【问题标题】:+= operator overloading c++ [closed]+= 运算符重载 C++ [关闭]
【发布时间】:2015-12-21 22:02:06
【问题描述】:

这是一个表示带有运算符重载的分数的代码

class Fraction
{
private:
int _counter, _denominator;
public:
Fraction(int _x, int _y);

Fraction & operator+=(int b)
{
    _counter = _counter + b*_denominator;
    return  *this;
}

Fraction & operator-=(int b)
{
    _counter = _counter - b*_denominator;
    return  *this;
}
};

Fraction::Fraction(int _x, int _y)
{
    _counter = _x;
    _denominator = _y;
}


void main()
{
    Fraction *f = new Fraction(2, 4);

    f += 5;
}

谁能告诉我为什么运算符+=重载不起作用?

【问题讨论】:

  • 您需要使用*f += 5;f->operator+=(5);
  • f 是一个绝对没有理由的指针。这就是问题所在。
  • 你为什么使用new?尽可能使用具有自动存储(即堆栈)的变量。
  • 或者更好,不要使用new:Fraction f(2, 4); f += 5;
  • 用完指针后,别忘了删除它:delete f;。另外,你可能是shouldn't start names with underscores

标签: c++ overloading operator-keyword


【解决方案1】:

您正在重载 Fraction 对象的运算符,但将 5 添加到 Fraction * 对象 - 一个指向 Fraction 的指针。

这样的事情会起作用:

(*f) += 5;

【讨论】:

    【解决方案2】:

    如果你实现operator+=()你应该知道它并自己使用它,所以这段代码:

    _counter = _counter + b*_denominator;
    

    最好写成:

    _counter += b * _denominator;
    

    因为它更短,更简洁。

    关于错误:使用对象而不是指针,因为这不是java:

    int main() // main() must return int
    {
       Fraction f(2, 4);
       f += 5;
    }
    

    【讨论】:

    • “应该写成” 为什么?
    • @LightnessRacesinOrbit 它更短更简洁
    • @Slava:所以可能而不是应该
    • 另外,在类的+= 定义中的数据成员上使用+= 是有意义的。
    • 但是你为什么要发表一个基本上不相关和误导性的陈述?先回答问题,不行吗?
    猜你喜欢
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多