Search code examples
c++operator-overloadingfractions

Overloading operator whose parameter is not class or enum


I want to overload operator like this:

fraction operator / (int a, int b) // error here
{
return fraction(a,b);
}

(Not inside fraction class). But the compiler says:

[Error] 'fraction operator/(int, int)' must have an argument of class or enumerated type.

Can I get around this? (Just want when I write like 1/3 to convert into fraction(1,3) not fraction(1/3) (1/3 which equal 0.3333333 in float so when converting back into fraction, I will get 16666667/50000000, not 1/3)


Solution

  • I want to overload operator like this:

    fraction operator / (int a, int b) // error here
    

    You may not do what you want, as the compiler says.

    Can I get around this?

    Want something else. There's no way to change division of two int in C++.

    You can just write fraction(1, 3). If you would like something shorter to write, then you could use a user defined literal: 1_frac / 3.


    not fraction(1/3) (1/3 which equal 0.3333333 in float so when converting back into fraction

    1/3 is not a float. It equals 0.