[英]assignment operator in c++
假設我有一些類A並從它派生出B:我想為B寫operator=
(讓我假設我的A類中有operator=
)是正確的方法:
B& B::operator=(const B& rhs)
{
if(this == &rhs) return *this;
((A&) *this) = rhs; //<-question
//some other options
return *this
}
如果我寫有什么區別
((A) *this) = rhs;
提前致謝
您的第二個代碼僅將*this
的A
部分(切片)復制到一個臨時變量中,對其進行分配,然后將其丟棄。 不是很有幫助。
相反,我將該行寫為:
A::operator=(rhs);
這很清楚它正在調用基類版本。
在您實際上不知道基類是什么,以及它是否具有operator=
成員或friend或什么的情況下,模版分配可能會更好。
在這種情況下:
A* basethis = this;
*basethis = rhs;
更容易閱讀和理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.