If we define a Rational
class to represent rational numbers like following
1 | class Rational { |
And you want to support rational number arithmetic like mutiplication, your instinct tells you to implement it as a member function
1 | class Rational { |
This seems ok but actually when you try to use it, you will realize there is an issue
1 | Rational oneEighth(1, 8); |
The last operation doesn’t compile! It’s because the last line is equivalent to result = 2.operator*(oneHalf)
which is clearly an error. There is no operator*
defined for literal 2
.
If you define the constructor explicit
, then you will realize result = oneHalf * 2
won’t compile either because it fails to apply implicit type conversion to 2
.
What’s the solution? You need to define operator*
as non-member function, which will allow compiler to perform implicit type conversion for all arguments.
1 | class Rational { |
This way, all usage above will compile and work correctly.