Yes, you can overload such operators. But I'm not sure what you mean by "switch case". You can live with one overload if you have a conversion constructor
class MyClass{ ... // code for creating a MyClass out of an int MyClass(int n) { ... } ... inline const MyClass MyClass::operator+(const MyClass &addend) const { cout<<"Adding MyClass+MyClass"<<endl; ...//Code for adding MyClass with MyClass } ... };
No switch is needed at all. It is eligible if "MyClass" logically represents a number.
Please note that you must overload these operators with non-member functions. In your code, 5 + c1 will not work, because there is no operator that accepts int as the left side. Following will work
inline const MyClass operator+(const MyClass &lhs, const MyClass &rhs) {
Now, if you save the conversion constructor, you can add an int on either side with minimal code overhead.
Johannes Schaub - litb
source share