【问题标题】:why is the 'this' pointer dereferenced when returning by reference for operator assignment?为什么在通过引用返回运算符赋值时取消引用“this”指针?
【发布时间】:2020-04-01 07:41:01
【问题描述】:

当重载赋值运算符时,我注意到许多示例通过引用返回,然后返回一个延迟的“this”指针,如下所示:

Myclass &operator=(const Myclass &rhs){
    if(this==&rhs)
        return *this;
    value=rhs.value;
    return *this;
}

我不明白的是为什么它不只返回指针'this'而不取消引用它,因为指针的值是一个地址? 肯定返回一个取消引用的指针会返回指向的值,而不是标头中 & 指定的地址。

【问题讨论】:

  • 这样做是为了让您可以将调用链接到操作员。而返回类型中的&表示referencenot地址。 C++ 使用上下文敏感的语法,相同的语法在不同的上下文中可以有不同的含义。比如,在某些情况下& 表示“地址”,在其他情况下表示“引用”。
  • 这就是引用的工作方式。考虑int x; int &y = x;(注意x之前缺少&)。

标签: c++ pointers operator-overloading return-by-reference


【解决方案1】:

如果您将函数的返回类型更改为MyClass*,那么您可以在不取消引用的情况下返回thisthis 是一个指针,除非取消引用,否则只能将其作为指针返回。

【讨论】:

  • 我觉得这并不能回答这个问题。
【解决方案2】:

通过引用,我们可以写出类似的东西

Myclass a;
Myclass b;
Myclass c;

c = b = a;

另一方面,如果我们有:

Myclass* operator=(const Myclass &rhs){
    if(this==&rhs)
        return *this;
    value=rhs.value;
    return this;
}

那么b = a 的结果是一个Myclass 指针,它通常不能直接分配给Myclass 实例。它最终会等同于

Myclass a;
Myclass b;
Myclass c;

Myclass* temp = b = a;
c = temp;         // compile error here

那么我们最多可以这样做:

c = *(b = a);

这肯定更尴尬。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-04
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2011-03-07
    • 1970-01-01
    • 2012-02-22
    相关资源
    最近更新 更多