在运算符重载C ++中返回引用与否之间有什么区别?

时间:2013-05-06 19:01:06

标签: c++ reference operator-overloading

我试图找出&的目的是什么?关于返回类型。我的意思是,考虑下面的代码,如果我删除&来自运算符重载函数。

    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;
        }
    }

};

我删除它并编译它,它编译没有任何错误.Actualy它在两种情况下给出了相同的结果,例如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;
}

那么,是否有人可以帮助我了解&amp;的目的在左侧 ?提前致谢。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果您没有返回引用,则隐含地进行额外的不必要的复制。