#include using namespace std; /* This class has methods defined completely inside * the class definition. This can make the class * definition long and cumbersome, and in most * cases should be avoided. But you can do it! * The "inline" keyword specifies that instead of * making a function call, the compiler should * insert the code where it is needed, and will * improve performance for very short functions. * But, the optimizer can automatically inline * functions, so the keyword is not really required. * Now if you see it in code, you know what it * means! */ class WeirdInt { public: inline int operator+ (int other){ return 42; } inline WeirdInt operator= (int data) { val = data; return *this; } inline operator int() const { return val; } private: int val; }; int main(){ WeirdInt x; x = 5; int y = x; // y is 5. Prints out 5. cout << y << endl; // 4 is an int. x will be converted to an int // 4+5 is 9. This will print out 9. cout << 4 + x << endl; // x is a WeirdInt and 4 is an int // class WeirdInt has an overloaded operator+ // It will be called, and the result is 42 cout << x + 4 << endl; // Prints 42 /* * So, x is 5, and 4 + x is 9 * But x + 4 is 42! * This kind of thing should be avoided, because * it makes programs confusing. Be careful not * to generate similar situations with operator * overloading! With power comes responsibility. */ return 0; }