什么是赋值运算符的返回类型? [英] what is return type of assignment operator?

查看:35
本文介绍了什么是赋值运算符的返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 C++.我对赋值和取消引用运算符的返回类型有点困惑.我正在关注 C++ Primer 这本书.在各种场合,作者说赋值运算符的返回类型是对左手操作数类型的引用,但后来又说返回类型是左手操作数的类型.我已经提到了 C++11 Standard Sec.5.17,其中返回类型被描述为左值引用左手操作数".

I am just starting C++. I am a bit confused about the return type of assignment and dereference operator. I am following the book C++ Primer. At various occasions, the author says that the return type of assignment operator is reference to the type of left hand operand but later on, he says that the return type is the type of the left hand operand. I have referred C++11 Standard Sec. 5.17, where the return type is described as "lvalue referring to left hand operand".

同样,我无法弄清楚取消引用是返回指向的对象还是对对象的引用.

Similarly, I can't figure out whether dereference returns the pointed-to object or the reference to the object.

这些陈述是等价的吗?如果是,那又如何?任何解释将不胜感激.

Are these statements equivalent? If so, then how? Any explanation would be appreciated.

推荐答案

标准正确定义了赋值运算符的返回类型.实际上,赋值操作本身并不依赖于返回值——这就是返回类型不容易理解的原因.

The standard correctly defines the return type of an assignment operator. Actually, the assignment operation itself doesn't depend on the return value - that's why the return type isn't straightforward to understanding.

返回类型对于链接操作很重要.考虑以下结构:a = b = c;.这应该等于 a = (b = c),即 c 应该被分配到 bb变成a.将其重写为 a.operator=(b.operator=(c)).为了使 a 的赋值正常工作,b.operator=(c) 的返回类型必须是对内部赋值结果的引用(它也适用于 copy但这只是不必要的开销).

The return type is important for chaining operations. Consider the following construction: a = b = c;. This should be equal to a = (b = c), i.e. c should be assigned into b and b into a. Rewrite this as a.operator=(b.operator=(c)). In order for the assignment into a to work correctly the return type of b.operator=(c) must be reference to the inner assignment result (it will work with copy too but that's just an unnecessary overhead).

解引用运算符的返回类型取决于您的内部逻辑,以适合您需要的方式定义它.

The dereference operator return type depends on your inner logic, define it in the way that suits your needs.

这篇关于什么是赋值运算符的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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