Operator function confusion

And I quote:

A constructor with one argument provides a conversion function. For example,
the following constructor enables automatic conversion of integer data into
Fraction-class format:


Fraction(int n) {set(n, 1);};

I am reading this in a book and it says that with that constructor function in place, this line should be valid: Fraction f1 = 1 + Fraction(1, 2); but my compiler reports an error: No operator "+" matches these operands. On the other hand, this line of code works just fine: Fraction f1 = Fraction(1, 2) + 1;. So as you would assume I'm a bit confused. Is the book just plain wrong or am I missing something crucial?

If I need to supply more info on the implementation of the class just say it.

Thanks.
I don't think the book is wrong, it's actually a compiler dependent issue. It depends on how compiler treats expression of "1 + Fraction(1,2)".

Your compiler treats it as "(Fraction)(1 + Fraction(1,2))", so global function operator+(int, int) is used here and failed.

other compilers might treat it as "Fraction(1) + Fraction(1,2)", and Fraction::operator+() is used here if it's defined.
Topic archived. No new replies allowed.