c++ - 重载 + 和 << 运算符的有理数 (p/q) 类
问题描述
我想添加两个有理数并使用重载运算符 + 和 << 以 p/q 的形式显示它们。我正在使用朋友功能,因为添加和显示功能采用多种不同类型的参数。在加法函数中,我正在执行正常的分数加法,就像我们在现实生活中所做的那样。但是当我运行代码时,我得到一个错误,无法将 Rational 转换为 Rational(),
错误: Rational.cpp: In function 'int main()': Rational.cpp:51:15: error: assignment of function 'Rational R3()' R3 = R1 + R2; Rational.cpp:51:15: error: cannot convert 'Rational' to 'Rational()' in assignment*
我不知道为什么它这么说.... ??
C++
#include <iostream>
using namespace std;
class Rational
{
private:
int P;
int Q;
public:
Rational(int p = 1, int q = 1)
{
P = p;
Q = q;
}
friend Rational operator+(Rational r1, Rational r2);
friend ostream & operator<<(ostream &out, Rational r3);
};
Rational operator+(Rational r1, Rational r2)
{
Rational temp;
if(r1.Q == r2.Q)
{
temp.P = r1.P + r2.P;
temp.Q = r1.Q;
}
else
{
temp.P = ((r1.P) * (r2.Q)) + ((r2.P) * (r1.Q));
temp.Q = (r1.Q) * (r2.Q);
}
return temp;
}
ostream & operator<<(ostream &out, Rational r3)
{
out<<r3.P<<"/"<<r3.Q<<endl;
return out;
}
int main()
{
Rational R1(3,4);
Rational R2(5,6);
Rational R3();
R3 = R1 + R2;
cout<<R3;
}
解决方案
这个
Rational R3();
声明一个被调用的函数R3
,它返回 aRational
并且不接受任何参数。它没有定义R3
为默认构造的Rational
. 将行更改为以下任何一项
Rational R3;
Rational R3{};
auto R3 = Rational();
auto R3 = Rational{};
推荐阅读
- blockchain - 由于状态根哈希不匹配,TP 在区块被拒绝后未接收交易 Hyperledger Sawtooth
- javascript - Javascript中的XOR密码解密
- java - 在 JSON 中检索单个深层数组
- javascript - 使用 JavaScript 更新画布时如何避免分离的 HTMLCanvasElements?
- docker - pod重启时自动下载包
- single-sign-on - AWS Cognito:支持 SSO IdP 启动的工作流程
- python - 无法使用请求登录网站
- windows - 在 Windows 上模拟进程替换的理想方法是什么?
- php - 如何按顺序检索json数据
- swift - Firebase分页数据返回相同的数据?