运算符的返回类型= - 引用或值? [英] Return type of operator= - reference or value?

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

问题描述

从函数返回函数operator =

What is the difference between returning from function "operator="

by reference
by value

?这两个版本似乎在下面的示例中产生正确的结果。

? Both version seems to yield a correct result in the example below.

#include <iostream>
using namespace std;

class CComplexNumber{
    float m_realPart;
    float m_imagPart;
public:
    CComplexNumber(float r,float i):m_realPart(r),m_imagPart(i){}

    //the following can be also 
    //CComplexNumber& operator=(const CComplexNumber& orig){
    CComplexNumber operator=(const CComplexNumber& orig){
        if (this!=&orig){
            this->m_realPart=orig.m_realPart;
            this->m_imagPart=orig.m_imagPart;
        }
        return *this;
    }

    friend ostream& operator<<(ostream& lhs,CComplexNumber rhs){
        lhs<<"["<<rhs.m_realPart<<","<<rhs.m_imagPart<<"]"<<endl;
    }
};

int main() {
    CComplexNumber a(1,2);
    CComplexNumber b(3,4);
    CComplexNumber c(5,6);

    a=b=c;
    cout<<a<<b<<c;

    return 0;
}


推荐答案

strong>复制。通过引用返回返回对象本身。

Returning by value returns a copy of the object. Returning by reference returns the object itself.

您要使用哪一个取决于您想如何使用返回的值。如果要修改它而不影响原始对象(返回后),请按值返回;否则返回引用。

Which one you want to use depends on how you want to use the value that was returned. If you want to modify it without affecting the original object (after returning), return by value; otherwise return by reference.

使用operator =成员函数时的约定是通过引用返回。这允许您对对象进行链式操作:

The convention when using the operator= member function is to return by reference. This allows you to chain operations on the object:

CComplexNumber a(1,2);
CComplexNumber b(3,4);

(a = b) *= 2; //Assignment of b to a, then scale by 2

现在, , * = 不会修改值 a ,因为副本通过引用返回, b 将分配给 a a 本身将缩放为2。

Now, with return by value after the assignment, the *= would not modify the value a, since a copy of a would be scaled by 2. With return by reference, b would be assigned to a and a itself would be scaled by 2.

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

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