Assignment Operator Overloading in C++ Syntax Explanation

时间:2018-05-28 18:48:34

标签: c++ reference operator-overloading this

I am new to C++. I need some help understanding this code snippet.

Queue & operator=(const Queue &rhs)
{
    front = rhs.front;
    nWaiting = rhs.nWaiting;
    for (int i = front, j = 0; j < nWaiting; j++) 
    {
        elements[i] = rhs.elements[i];
        i = (i + 1) % 100;
    }
    return *this;
}

I am unable to understand why there is an '&' before operator in the code and how does this work along with *this.

I understand operator overloading. For eg. the code below for addition operation overloading. However I don't understand why '&' is required for assignment operator (=) overloading.

V3 operator* (const double factor, const V3 &b)
{
    return (b * factor);
}

3 个答案:

答案 0 :(得分:2)

&表示操作符返回引用(原始对象),而不是值(对象的副本)。这避免了不必要的复制。 this是指向调用运算符的对象本身的指针,因此return *this表示返回对=左侧对象的引用。

这允许操作符被链接,如a = b = 1。这会先将{1}分配给b,然后返回对b的引用。然后将b的值分配给a。因此ab都是1。

答案 1 :(得分:1)

The reference means that avoid copying the object. As a result, it will return a reference to the same object. Moreover, it will provide lvalue as a result. And if you think about it, that's what you want to happen when the assignment operator is used.

Every object in C++ has access to its own address through this pointer.

That means that the you return the object itself.

If your question is why we use *this instead of this, then this happens because you need to dereference the pointer first, since the return type is a reference (and not a pointer for example).

答案 2 :(得分:0)

运算符可以没有任何返回值,但是通常在

中启用链接
c = (a = b);

这会将b分配给a,然后将operator=来电的返回值分配给c。由于您不想制作不必要的副本,因此返回对象本身的引用,即*this。实际上,避免复制并不是使用引用的唯一原因,但如果您考虑

(d = e) = f;

然后这只会按预期工作(首先将e分配给d然后将f分配给d)如果operator=返回非const (!)参考。

请注意operator*是不同的,因为它不应该修改它所调用的对象,而是返回一个新实例(因此在&的返回中没有operator* )。