【问题标题】:Need Help Operator Overloading So I Can Display Functions需要帮助运算符重载,以便我可以显示函数
【发布时间】: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 &amp;robj

标签: c++ function operator-overloading


【解决方案1】:

首先,改变

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&lt;&lt;函数,我会去掉display()这个成员函数。它不会(不应该)为您提供比使用 operator&lt;&lt; 函数更多的功能。

给定

rational 1

使用

r.display();

应该给你同样的输出

cout << r << endl;

有关运算符重载的更多详细信息,请参阅What are the basic rules and idioms for operator overloading?

【讨论】:

  • 我让它工作了,但我有一个函数,它有一个像这样传递的变量:r1.add(r2)。我将如何在 >> 重载中定义它?将 r1 (r2) 放在 main 中会给我一个错误。
  • @LunyJake,很高兴听到你的想法起作用了。我认为为这样的问题创建另一个帖子会更好。
猜你喜欢
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 2010-11-23
  • 1970-01-01
相关资源
最近更新 更多