在类中使用带有重载算术运算符的ostream

时间:2018-11-03 10:47:39

标签: c++ operator-overloading

我有课程Rational,其片段是:

class Rational {
private:
    int numerator;
    int denominator;
    void saveAsIrreducible();
    gcd(int x, inty);
public: 
    Rational(int numerator, int denominator=1);
    Rational operator*(Rational &r);
    friend ostream& operator<<(ostream &output, Rational &r);
}

实施:

Rational::Rational(int numerator, int denominator) {
    this->numerator = numerator;
    this->denominator = denominator;
    this->saveAsIrreducible();
}

Rational Rational::operator*(Rational &r) {
    Rational r2 = Rational((this->numerator*r.numerator), (this->denominator*r.denominator));
    return r2;
}

ostream& operator<<(ostream &output, Rational &r) {
    output << r.numerator;

    if(r.denominator!=1)
        output << "|" << r.denominator;

    return output;
}

void Rational::saveAsIrreducible() {
    int greatestCommonDivisor = gcd(numerator, denominator);
    numerator = numerator/greatestCommonDivisor;
    denominator = denominator/greatestCommonDivisor;
    if(numerator > 0 && denominator < 0) { /* for example for 3|-2, after arithmetic operations */
        numerator = -numerator;
        denominator = -denominator;
    }
}

int Rational::gcd(int x, int y) {
    while(y!=0) {
        int r = x%y;
        x = y;
        y = r;
    }

    return x;
}

我在将*cout一起使用运算符时遇到问题。例如,它可以工作:

Rational r1(3,5), r2(3,6);
Rational r3 = r1*r2;
cout << r3 << endl;

输出正确。但是当我尝试这样做时:

Rational r1(3,5), r2(3,6);
cout << r1*r2 << endl;

我从编译器中收到很多错误:

Rational.cpp|186|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Rational')|

Rational.cpp|186|error: invalid initialization of non-const reference of type 'Rational&' from an rvalue of type 'Rational'|

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

重载的operator<<Rational&作为参数。

因此,对于以下语句:

Rational r3 = r1*r2;
cout << r3 << endl;

r3是一个左值(包含r1*r2的结果),其引用传递给operator<<并且成功。

但是当您执行以下操作时:

cout << r1*r2 << endl;

您没有传递对operator<<的引用,因为operator*返回了一个临时值。因此失败了。

要解决此问题,可以使用const Rational &作为operator<<的参数。您将必须同时更改operator<<的声明和定义。