首页 > 解决方案 > 通过引用返回对象的工作原理

问题描述

据我了解,这是我的参考 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++oopreferenceoperator-overloading

解决方案


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


推荐阅读