在赋值运算符重载而不

在赋值运算符重载而不

本文介绍了为什么我们在赋值运算符重载而不是在正负运算中使用引用返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我在书本和网络上阅读的那样,在C ++中,我们可以使用这些原型(作为class Money的成员函数)重载"plus"或"minus"运算符:

const Money operator +(const Money& m2) const;

const Money operator -(const Money& m2) const;

,并为赋值运算符提供以下信息:

const Money& operator =(const Money& m2);

为什么在赋值运算符重载而不在加号和减号运算符中使用对Money对象的引用作为返回值?

解决方案

从分配中返回引用允许链接:

a = b = c;  // shorter than the equivalent "b = c; a = b;"

(如果操作员返回新值的副本,这在大多数情况下也可以使用,但是通常效率较低.)

我们无法从算术运算中返回引用,因为它们会产生新的值.唯一(明智的)返回新值的方法是按值返回它.

像您的示例一样,返回常量值可以防止移动语义,所以不要这样做.

As I read in books and in the web, in C++ we can overload the "plus" or "minus" operators with these prototypes (as member functions of a class Money):

const Money operator +(const Money& m2) const;

const Money operator -(const Money& m2) const;

and for the assignment operator with:

const Money& operator =(const Money& m2);

Why use a reference to a Money object as a return value in the assignment operator overloading and not in the plus and minus operators?

解决方案

Returning a reference from assignment allows chaining:

a = b = c;  // shorter than the equivalent "b = c; a = b;"

(This would also work (in most cases) if the operator returned a copy of the new value, but that's generally less efficient.)

We can't return a reference from arithmetic operations, since they produce a new value. The only (sensible) way to return a new value is to return it by value.

Returning a constant value, as your example does, prevents move semantics, so don't do that.

这篇关于为什么我们在赋值运算符重载而不是在正负运算中使用引用返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:20