As per Deitel's 9ed C++ How to program, p. 439-440:
A binary operator can be overloaded as a non-static member function with one parameter or as a non-member function with two parameters (one of those parameters must be either a class object or a reference to a class object).
So, what other sort of object is there beside a class object or a reference to a class object? I cannot think of anything.
So, what other object is there beside class object or a reference to a class object?
There are fundamental types defined by the language, such as int
, double
. Instances of fundamental types are also objects.
Let's say you have:
struct Foo { ... };
You can overload the operator+
function as non-member functions
Foo operator+(Foo , int);
Foo operator+(Foo& , int);
Foo operator+(int, Foo);
Foo operator+(int, Foo&);
etc. In all these cases, one of the arguments is a Foo
or a Foo&
. It can also be Foo const&
. However, you cannot overload
int operator+(int, int);
since neither of the argument types is a class or a reference to a class.
It means you can't (re)define the built-in operators like int operator+(int a, int b);
. Note that the description is incomplete, one or both parameters can also be an enum
.
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