Refer C++ FAQ lite
It states for binary infix arithmetic operators :
member functions don't allow promotion of the left hand argument, since that
would change the class of the object that is the recipient of the member
function invocation
Can someone please explain why this is so ? Why is there a constrain on the type of first argument ?
Thank you.
Consider this:
struct Number {
Number(int val) : val(val) { } // *Not* explicit
int val; // Everything public to simplify example
Number operator+(Number const& other) const { return val + other.val; }
};
Number n(42);
Number result = 32 + n; // Doesn't compile
But if we removed the member operator and made it a free function instead:
Number operator+(Number const& a, Number const& b) { return a.val + b.val; }
Number n(42);
Number result = 32 + n; // Compiles!
Suppose you have a type Foo
so that for Foo f; int n;
Foo f; int n;
both of the expressions f + n
and n + f
make sense.
By overloading the member operator+
, you can only ever implement f + n
:
struct Foo
{
Bar operator+(int n) const; // binds to "Foo + int"
// ...
};
You can never get the other version, int + Foo
, from a member operator. The solution is to define the free operator, which can be made for any signature that involves at least one user-defined type. In fact, we can recycle the member operator like so:
Bar operator+(int n, Foo const & f) // binds to "int + Foo"
{
return f + n; // recycle existing implementation
}
When you only have a free operator overload, it often makes sense to make it a friend
of Foo
so that it can access the interna of that class. In our case we didn't need this because we just pass the call on to the member operator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.