开发者

prefix operator overloading

I'm overloading the ++ prefix operator using a member function. Here's the prototype:

Test &operator++();

But my doubt comes when I use it for my object like below:

Test t;
++t;

As far I have learned that for any operator overloaded by a member function there should be a object of that same class on left side of that o开发者_StackOverflow中文版perator. But when I am calling this ++ prefix overloaded operator, I don't need any object of Test class on the left side.

Why?


Test& operator++();

is always the prefix operator by C++ standard.

In order to override the suffix operator, you need to use another signature:

Test& operator++(int);

These signature are known by the compiler and it will correctly override the right operator.


You just learned incorrectly. How could you have something on the left side of a unary prefix operator?

The same goes for operator~, operator-- and operator!. You don't have anything on the left side of them either.


Then you have learnt wrong...

Your example is fine; that is indeed how to declare an overload for the pre-increment operator.


As far I have learned that for any operator overloaded by a member function there should be a object of that same class on left side of that operator.

That would hold for any binary operator. Pre- and post-incrementations, as well as the dereference operator (*obj) are unary operators. They have a single argument (either a function parameter or implied "this" parameter, depending on how you overload the operator) and for overloaded operators this only argument must be of a class type.

But when I am calling this ++ prefix overloaded operator, I don't need any object of Test class on the left side.

Unary operators don't have a "left" and "right" sides (operands), they only have one operand.


Remember that in your case:

++t;

means just:

t.operator++();

So - in some twisted thinking - t is indeed on the left side. :)


Operator overloading provides a syntax that is slightly different to any other member (or non-member) function. Whether you implement the pre-increment as a member function or as a free function, you are implementing pre-increment, and the syntax for pre-increment is ++obj.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜