【发布时间】:2019-11-18 23:13:25
【问题描述】:
我一直在试图弄清楚如何重载
这些是我试图重载的行:
cout << "Testing the compare() member function, found:" << endl;
if (r1.compare(r2) == 1)
cout << r1.display() << " is greater than " << r2.display() << endl;
else if (r1.compare(r2) == 0)
cout << r1.display() << " is equal to " << r2.display() << endl;
else if (r1.compare(r2) == -1)
cout << r1.display() << " is less than " << r2.display() << endl;
cout << "Testing the four arithmetic member functions:" << endl;
cout << "r1 + r2 = " << r1.display() << " + " << r2.display() << " = " << r1.add(r2) << endl;
cout << "r1 - r2 = " << r1.display() << " - " << r2.display() << " = " << r1.subtract(r2) << endl;
cout << "r1 * r2 = " << r1.display() << " * " << r2.display() << " = " << r1.multiply(r2) << endl;
cout << "r1 / r2 = " << r1.display() << " / " << r2.display() << " = " << r1.divide(r2) << endl;
每次调用函数时都会发生错误。下面是函数的代码:
void rational::display()
{
int gcd = GCD();
if (denom < 0)
{
num = -num;
cout << num / gcd << " / " << denom / gcd << endl;
}
else if (num == 0)
cout << num << endl;
}
rational rational::add(const rational &r2) const
{
rational sum;
sum.num = (num * r2.denom) + (r2.num * denom);
sum.denom = denom * r2.denom;
return sum;
}
乘法、除法和减法函数与加法相同,只是更改了符号和变量名以匹配运算。我的重载运算符是这样设置的:
ostream& operator<< (ostream& out, rational &robj)
{
out << example code << example code;
return out;
}
任何帮助将不胜感激。这是我第一次发布,所以如果我需要发布更多我的代码,我会的。谢谢!
【问题讨论】:
-
出现什么错误?尽可能具体。
-
所以对于这一行: cout }' and 'void')
-
不确定您的错误,但请在您的流操作符中尝试
const rational &robj。
标签: c++ function operator-overloading