簡體   English   中英

通過引用返回對象的工作原理

[英]How works returning an object by reference

據我所知,這是我的參考 SomeClass &ref=b; 之后 b = ref; 然后 c = b; SomeClass &ref2=c; 然后 c=ref2 。 但是當 b=ref 或 c = ref2 時,我是否調用了操作符 = 女巫? 類似的東西 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;

}

如果你有:

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")

通過在SomeClass重載運算符 = ,您正在執行復制賦值lhs = rhs (例如: c = b , c 是lhs , b 是rhs )。 因為它返回匹配SomeClass& operator=預期參數類型的引用,所以您可以鏈接多個復制賦值,例如c = b = a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM