开发者

Why are operators sometimes stand-alone and sometimes class methods?

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 w开发者_高级运维hen you do it the other?


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 have a binary operator like +, you normally want type conversions to be performed on both operands. For example, a string concatenation operator needs to be able to convert either or both of its operands from a char * to a string. If that is the case, then it cannot be a member function, as the left hand operand would be *this, and would not have a conversion performed.

E.g.:

operator+( a, b );  // conversions performed on a and b
a->operator+( b );  // conversion can only be performed on b


If the operator is defined outside of a class it's considered global, and allows you to have other types appear on the left hand side of the operator.

For example, given a class Foo, with a global operator + you could do:

Foo f;
Foo f2 = 55 + f;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜