【问题标题】:How works returning an object by reference通过引用返回对象的工作原理
【发布时间】:2020-02-18 08:59:24
【问题描述】:

据我了解,这是我的参考 SomeClass &ref=b;之后 b = ref;然后 c = b;某类 &ref2=c;然后 c=ref2 。但是当 b=ref 或 c = ref2 时,我是否调用了 operator = 女巫我已经重新加载?类似的东西 a.operator=(ref) ?

class SomeClass
{
public:
    SomeClass()
    {
        a = 5;
    }
    SomeClass(int l_a)
    {
        a = l_a;
    }

    SomeClass& operator=(const SomeClass& l_copy)
    {
        this->a = l_copy.a;
        return *this;
    }

    int a;
};

int main()
{
    SomeClass a;
    SomeClass b(1);
    SomeClass с(6);
    с = b = a;

}

【问题讨论】:

  • c=b=a;c=(b=a); 相同,与c.operator=(b.operator=(a)); 相同。没有operator= 调用a。请注意,赋值具有从右到左的关联性。因此b.operator=(a) 返回一个对b 的引用,该引用用作c.operator= 调用的参数。
  • 我已经问过当 b = ref (SomeClass &ref=b) 时对象如何通过引用传输我是否使用重新加载的运算符 = ?
  • 什么是“重载”运算符?
  • 您是在询问SomeClass& ref = b; b = ref; 的情况吗?如果是这样,为什么您的代码会做一些完全不同的事情?其中没有ref。请编辑代码以匹配您的问题。
  • @ZELIBOBA 您也可以将c=b=a; 重写为b=a; SomeClass& ref=b; c=ref;,效果相同。最后c=bc=ref没有区别。仍然不清楚您的问题,抱歉。

标签: c++ oop reference operator-overloading


【解决方案1】:

通过重载 SomeClass 中的运算符 =,您正在执行复制赋值 lhs = rhs(例如:c = b,c 是 lhs,b 是 rhs)。因为它返回匹配SomeClass& operator= 预期参数类型的引用,所以您可以链接多个复制分配,例如c = b = a

【讨论】:

    【解决方案2】:

    如果你有:

    void operator=(const SomeClass& l_copy)
        {
            this->a = l_copy.a;
        }
    

    那么您的分配操作将被限制为:

    b = a;
    c = b;
    

    通过返回引用,您可以链接分配,如下所示:

    c = b = a;
    // c.operator = (b.operator = (a));
    
    //1: b.operator= ("ref a")
    //2: c.operator= ("ref b")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      相关资源
      最近更新 更多