需要帮助操作员过载,这样我才能显示功能
Need Help Operator Overloading So I Can Display Functions
我一直在想如何重载<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;
请参阅运算符重载的基本规则和习惯用法是什么?有关运算符重载的更多详细信息。
相关文章:
- 链表中的显示功能无法正常工作
- 显示循环双端队列的功能
- OpenGL Glut显示功能在Mojave上显示黑屏
- 为什么我的显示功能会终止程序?
- 通过功能进行2D矢量输入和显示
- 错误:调用'strcmp'没有匹配函数(尝试设置显示用户信息功能)
- 需要帮助操作员过载,这样我才能显示功能
- Qt C++括号匹配和突出显示当前线路功能无法协同工作
- 如何在控制台应用程序中添加滚动功能以显示更大的输入
- "hello triangle"未显示。是否有某些功能未正确使用?
- 氧气显示功能简要概述
- 我的显示功能有问题
- 单个模板功能,用于显示不同容器的内容
- 编写一个递归功能,该功能采用数组并以相反顺序显示元素,而无需在末尾启动数组的索引
- C 尝试使用模板输出功能来显示不同类型的数据
- 如何在C++中实现按级别计数/显示节点的功能
- 使用循环显示虚拟功能
- 休息后显示功能
- 由于显示功能而引起的非法间接误差
- 功能显示问题