为什么 'this' 在这种情况下需要取消引用? (赋值运算符)

Why does 'this' need to be dereferenced in this case? (assignment operator)

所以这是一个用户定义向量的复制赋值示例[摘自 Bjarne Stroustrup 的“C++ 之旅(第 2 版)]class:

Vector& Vector::operator=(const Vector& a) // copy assignment
{
    double* p = new double[a.sz];
    for (int i=0; i!=a.sz; ++i)
        p[i] = a.elem[i];
    delete[] elem; // delete old elements
    elem = p; // here elem is the vector's data holding member array
    sz = a.sz;
    return *this;
}

'This' 是一个指针,所以取消引用它实际上应该给我们它指向的当前对象。在期望引用所述对象的情况下,如何将对象作为 return 值接受?

this是一个指针,指向被赋值的对象。函数 returns 对象的引用。所以你需要解引用指针来获取对象的左值。

this是指针类型。您的函数 returns 对 Vector 的引用。要将指针转换为左值,您需要取消引用它。

'This' is a pointer, so dereferencing it should actually give us the current object it points at.

是的。

How does an object gets accepted as a return value in a case when a reference to said object is expected?

与任何其他引用的方式相同。

int x = 3;
int& ref = x;  // just fine

Why does 'this' need to be dereferenced in this case? (assignment operator)

需要取消引用指针以获得指针对象,与函数 returning 引用类型几乎没有关系,只是说如果你 没有 取消引用指针,你必须 returning 指针,所以 return 类型必须是 Vector*.