【发布时间】:2013-07-29 15:20:14
【问题描述】:
所以,我得到了 obj1 + obj2 的类内运算符重载:
fraction operator+ (fraction op);
同样,cout
ostream& operator<< (ostream& os, fraction& frac);
但是,如果我尝试将两者结合起来,一切都会崩溃。
fraction.cpp:77:27: error: no match for ‘operator<<’ in
‘std::operator<< [with _Traits = std::char_traits<char>]((* & std::cout), ((const char*)"Sum: "))
<< f1.fraction::operator+(f2)’
代码如下:
#include <iostream>
using namespace std;
class fraction
{
private:
int n, d;
public:
fraction ()
{
this->n = 1;
this->d = 0;
}
fraction (int n, int d)
{
this->n = n;
this->d = d;
}
int getNumerator ()
{
return n;
}
int getDenominator ()
{
return d;
}
fraction operator+ (fraction op)
{
return *(new fraction(this->n*op.d + op.n*this->d, this->d*op.d));
}
fraction operator- (fraction op)
{
return *(new fraction(this->n*op.d - op.n*this->d, this->d*op.d));
}
fraction operator* (fraction op)
{
return *(new fraction(this->n*op.n, this->d*op.d));
}
fraction operator/ (fraction op)
{
return *(new fraction(this->n*op.d, this->d*op.n));
}
};
ostream& operator<< (ostream& os, fraction& frac)
{
int n = frac.getNumerator();
int d = frac.getDenominator();
if(d == 0 && n == 0)
os << "NaN";
else if(d == 0 && n != 0)
os << "Inf";
else if(d == 1)
os << n;
else
os << n << "/" << d;
}
int main ()
{
fraction f1(2, 3);
fraction f2(1, 3);
cout << f1 << " " << f2 << endl;
/*
cout << "Sum: " << f1+f2 << endl;
cout << "Difference: " << f1-f2 << endl;
cout << "Product: " << f1*f2 << endl;
cout << "Quotient: " << f1/f2 << endl;
*/
return 0;
}
帮助。 D:
【问题讨论】:
-
你在疯狂地泄漏内存!将
return *(new fraction(...));替换为return fraction(...);。 -
停止使用
new。可能摆脱您当前的学习材料以支持a decent one。 -
如果你想获取一个对象,不要使用
return *(new T()),只需使用return T()。 -
您的
ostream& operator<<不会返回os。 -
C++ 不是 java。正如其他人指出的那样,这就像一艘有纱门的船一样泄漏。