需要帮助操作员过载,这样我才能显示功能

Need Help Operator Overloading So I Can Display Functions

本文关键字:功能 显示 帮助 操作员      更新时间:2023-10-16

我一直在想如何重载<lt;运算符,这样我就可以显示我的rational类函数。

这些是我试图超载的线路:

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;
}

如有任何帮助,我们将不胜感激。这是我第一次发布,所以如果我需要发布更多的代码,我会的。谢谢

首先,更改

ostream& operator<< (ostream& out, rational &robj)

ostream& operator<< (ostream& out, rational const& robj)

然后,代替

cout << r1.display() << " is greater than " << r2.display() << endl;

使用

cout << r1 << " is greater than " << r2 << endl;

由于您已经有了上面的operator<<函数,我将去掉成员函数display()。它不会(不应该(为您提供比使用operator<<函数更多的功能。

给定

rational 1

的使用

r.display();

应该给你与相同的输出

cout << r << endl;

请参阅运算符重载的基本规则和习惯用法是什么?有关运算符重载的更多详细信息。