Search code examples
c++type-conversionbooleancomparison

C++ Fraction mixed comparison operator error


So I am new to c++ and trying to create a C++ fraction class with operations overloading. Everything has been fine up till I get an error on the less than comparison line in the main function:

    Fraction someNum(15, 9);

    ......

    if (someNum > 1)
        cout << "15/9 > 1." << endl;

    if (1 < someNum) //throws error
        cout << "1 < someNum." << endl;

Error:

    operator<(const error_condition& __lhs,
            ^~~~~~~~
    c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\system_error:274:3: note:   no known conversion for argument 1 from 'int' to 'const std::error_condition&'

The strange thing is that the bigger than comparison prints the output correctly and does not throw an error despite that they are both mixed comparisons.

Here are their corresponding code in my other .cpp file:

    //lesser than
    bool Fraction::operator<(Fraction right) {
    return (num * (denom * right.denominator())) < (right.numerator() * (denom * right.denominator()));}
    //greater than
    bool Fraction::operator>(Fraction right) {
    return (num * (denom * right.denominator())) > (right.numerator() * (denom * right.denominator()));}

As you can see, the codelines are exactly the same except for the comparison operator involved. However, one throws an error and one does not. Once you take the last comparison output away, everything works correctly. I do not understand how to fix this at all...

Any pointers would be greatly appreciated. Please let me know if more information is needed.

Thank you!


Solution

  • You'll need a operator< that matches the order of the arguments as presented. The op> comparison in your example that works has the parameters in the opposite order, so it would match an op> overload similar to the op< overload parameter order you showed in your code.

    https://godbolt.org/z/bMMMX9

    struct Foo {};
    
    bool operator>(Foo, int);
    
    struct Bar {};
    
    bool operator>(Bar, int);
    bool operator>(int, Bar); // This one has the parameters in both orders
    
    int main() {
        Foo f;
        f > 1;
        1 > f; // doesn't work
    
        Bar b;
        b > 1;
        1 > b; // works
    }
    

    You can also put the comparator inside the struct as such:

    struct Bar {
        friend bool operator>(Bar, int);
        friend bool operator>(int, Bar);
    };