Check it out this code:
struct A
{
A operator+(A const& a) { cout << 1 << endl; return A(); }
A& operator++() { cout << 2 << endl; return *this; }
A operator++(int) { cout << 3 << endl; return *this; }
bool operator!() { cout << 4 << endl; return true; }
};
A operator+(A const& a, A const& b)
{ cout << 5 << endl; return A(); }
A& operator++(A& a) { cout << 6 << endl; return a; }
A operator++(A const& a, int) { cout << 7 << endl; return A(); }
bool operator!(A const& a) { cout << 8 << endl; return false; }
int main()
{
A a, b;
a + b; // Prints 1 instead 5
++a; // Ambiguity
a++; // Prints 3 instead 7
!a; // Prints 4 instead 8
return 0;
}
In every case, the in-class overload of an operator is choosen against any other out-class overload of the same operator, but the preincrement operator is different: it causes an ambiguity between the in-class and out-class overload.
Why?