c++操作符重载中返回引用和不返回引用的区别是什么?

what is the differences between returning reference or not in operator overloading C++

本文关键字:返回 引用 区别 是什么 操作符 c++ 重载      更新时间:2023-10-16

我试图弄清楚&在返回类型上。我的意思是,考虑下面的代码,如果我删除&操作符重载函数

    class Container
{

    public:
        int numElems;
        int *data;

    Container(int n):numElems(n){data=new int [numElems];}
    Container & operator=(const Container &rhs)
    {
        if(this!=&rhs)
        {
            if(data!=NULL)
                delete  [] data;
        numElems=rhs.numElems;
        data=new int [numElems];
        for (int i=0;i<numElems;i++)
        {   
            data[i]=rhs.data[i];    
        }
            return *this;
        }
    }

};

删除后编译,编译后没有任何错误。实际上,对于一个示例main:

,它在两种情况下给出相同的结果:
int main()
{
Container a(3);
Container b(5);
Container c(1);
cout<<a.numElems<<endl;
cout<<b.numElems<<endl;
cout<<c.numElems<<endl;
a=b=c;
cout<<a.numElems<<endl;
cout<<b.numElems<<endl;
cout<<c.numElems<<endl;
return 0;
}

那么,有没有人可以帮助我关于&在左边吗?提前感谢。

class foo {
    public:
        int val;
        foo() { }
        foo(int val) : val(val) { }
        foo& operator=(const foo &rhs) {
            val = rhs.val;
            return *this;
        }
        foo& operator++() {
            val++;
            return *this;
        }
};

void main() {
    foo f1(10), f2;
    (f2 = f1)++;
    std::cout << f1.val << " " << f2.val << std::endl;
}
输出:

10 11

删除引用时的输出:

10 10

返回一个引用比返回一个大对象的值要快得多。这是因为在底层,引用只是一个内存地址而如果按值返回它就需要深度复制

如果不返回引用,则隐式地进行了不必要的额外复制。