【问题标题】:A class for rational number (p/q) with overloading + and << operator重载 + 和 << 运算符的有理数 (p/q) 类
【发布时间】: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


【解决方案1】:

这个

Rational R3();

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

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

【讨论】:

  • 这不是“最麻烦的解析”。那是指more subtle issue。这并不是说它不适合初学者。
  • @PeteBecker 我很恼火:P 我知道我的知识存在漏洞,只是需要有人指出来。干杯
  • @PeteBecker 有时我需要一些尴尬才能学到一些东西=)。我真的认为“最烦人的解析”这个词更笼统,而我认为最烦人的解析实际上是它的一个特例。感谢您的链接,它有助于清除它
  • 不是故意让你难堪。在 Stackoverflow 上看到这被称为最令人烦恼的解析是很常见的;我也经常指出这不是它的原始含义。我对术语相当热心;当艺术术语失去其精确含义时,我可能过度担心不得不回填。请参阅任何提到“隐式演员”的帖子。
  • @PeteBecker 哦,对不起,我没有把它当作冒犯。我很高兴得到纠正,尤其是在使用错误术语时。恕我直言,正确使用这些术语至关重要。开玩笑的尝试很糟糕,当然不应该被纠正。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
相关资源
最近更新 更多