Why is that sometimes an operator override is defined as a method in the class, like
MyClass& MyClass::operatorFoo(MyClass& other) { .... return this; };
and sometimes it's a separate function, like
MyClass& operatorFoo(MyClass& first, MyClass& bar)
Are they equivalent? What rules govern when you do it one way and when you do it the other?
An operator is used to manipulate individual data items and return a result. These items are called operands or arguments. Operators are represented by special characters or by keywords.
Java doesn't allow user defined operator overloading because if you allow programmer to do operator overloading they will come up with multiple meanings for same operator which will make the learning curve of any developer hard and things more confusing and messing.
Operator Overloading in C++ In C++, we can make operators work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.
You cannot overload the following operators: . You cannot overload the preprocessor symbols # and ## . An operator function can be either a nonstatic member function, or a nonmember function with at least one parameter that has class, reference to class, enumeration, or reference to enumeration type.
If you want to be able to do something like 3 + obj
you have to define a free (non-member) operator.
If you want to make your operators protected or private, you have to make them methods.
Some operators cannot be free functions, e.g., operator->
.
This is already answered here:
difference between global operator and member operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With