重载预增量运算符时,是否必须返回对对象的引用? [英] Do I have to return a reference to the object when overloading a pre-increment operator?

查看:171
本文介绍了重载预增量运算符时,是否必须返回对对象的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用:

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

或者可以是:

  MyClass MyClass :: operator ++(); 

有什么区别?






感谢您的回答。我有另一个问题。



很多人都这样做:

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

这不是不合逻辑吗?请给出一些例子,如果你可以。



我知道第一个版本是预增量,第二个是后增量,但我问为什么第一个返回参考但第二个不是?

解决方案

不,你不是已经在您重载预增量运算符时返回对对象的引用。实际上你可以返回你想要的任何东西, MyClass int code>,无论如何。



这是一个设计问题 - 你必须问自己什么是最有用的东西给你的类的用户,你能



作为一般规则,类操作符是最有用的,当它们引起最小的混乱时,也就是说,当他们操作最类似于基本类型的操作符时。在这种情况下,基本类型的预增量运算符:

  int i = 7; 
j = ++ i;

递增变量,然后返回新值。如果这是你想要 MyClass 的唯一用途,那么返回你的类的副本就足够了。



但是,基本类型上的预递增运算符实际上返回一个左值。所以,这是合法的:

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

如果要支持此类操作,必须返回引用。



有没有特定的原因,你不想返回一个引用?这不是一个良好的概念为你的特定类吗?如果是,请考虑返回 void 。在这种情况下,这个表达式: ++ myObject 是合法的,而 myOtherObject = ++ myObject / p>

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.

解决方案

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.

这篇关于重载预增量运算符时,是否必须返回对对象的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆