Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

c++ - Do I have to return a reference to the object when overloading a pre-increment operator?

Can I use:

MyClass& MyClass::operator++ () {
    a++;  // private var of MyClass
    return (*this);
}

Or it can be:

MyClass MyClass::operator++ ();

What's the difference?


Thanks for answers. I have another issue.

Many people do something like that:

MyClass& MyClass::operator++();
MyClass MyClass::operator++(int);

Isn't it illogical? Please give some examples if you can.

I know that the first version is pre-increment and the second is post-increment, but i ask why the first one returns reference but the second one not? It is in the same code (class), and the same use of the code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, you don't have to return the reference to your object when you overload the pre-increment operator. In fact you may return anything you'd like, MyClass, int, void, whatever.

This is a design issue -- you must ask yourself what is the most useful thing to the users of your class that you are able to return.

As a general rule, class operators are the most useful when they cause the least confusion, that is, when they operate the most like operators on basic types. In this case, the pre-increment operator on a basic type:

int  i = 7;
j = ++i;

increments the variable and then returns the new value. If this is the only use you want MyClass to have, then returning a copy of your class is sufficient.

But, the pre-increment operator on a basic type actually returns an lvalue. So, this is legal:

int i = 7;
int *p = &++i;

If you want to support an operation like this, you must return a reference.

Is there a specific reason that you don't want to return a reference? Is that not a well-formed concept for your particular class? If so, consider returning void. In that case, this expression: ++myObject is legal, while this myOtherObject = ++myObject is not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...