【发布时间】:2021-09-13 15:09:11
【问题描述】:
我想添加两个有理数并使用重载运算符 + 和 错误: 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();->Rational R3;。您声明了一个不带参数并返回Rational的函数。 -
有必要创建自己的理性类型吗?可以用升压吗?它包含Rational 类型很长时间了。
-
经典 C++ 陷阱/错字:) godbolt.org/z/GsxbrKP4W
标签: c++ class operator-overloading friend-function