0
class Fraction {
public:
    int a, b;

    static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }

    Fraction() {}

    Fraction(int _a, int _b) : a(_a), b(_b) {
        // processing...
    }
};

Fraction operator+(const Fraction &x, const Fraction &y) {
    // processing...
    return Fraction(ta, tb);
}

std::ostream &operator<<(std::ostream &os, Fraction &f) {
    os << f.a << "/" << f.b;
    return os;
}

int main() {
    Fraction f1(1, 6);
    Fraction f2(1, 4);
    Fraction f3 = f1 + f2;
    cout << f3 << endl; // successful
    cout << f1 + f2 << endl; // error
}

As shown in the code, when I compile this code file, it shows an error in the last line

 error: invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and 'Fraction')
    cout << f1 + f2 << endl;

So how to overload operators in C++ when overloaded << and arithmetic operators are used continuously?

yanran
  • 33
  • 5

0 Answers0