首页 > 解决方案 > 重载 + 和 << 运算符的有理数 (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;

}

标签: c++classoperator-overloadingfriend-function

解决方案


这个

Rational R3();

声明一个被调用的函数R3,它返回 aRational并且不接受任何参数。它没有定义R3为默认构造的Rational. 将行更改为以下任何一项

 Rational R3; 
 Rational R3{};
 auto R3 = Rational();
 auto R3 = Rational{};

推荐阅读