【发布时间】: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