[英]C++ overloading assignment operator
我有一個名為Location
的類,我需要在其成員變量中添加一個CArray。 此更改導致需要重載賦值運算符。
有沒有辦法在進行更改之前復制此類類型中要復制的所有變量,而只需添加其他代碼即可復制CArray,而無需單獨復制每個成員變量?
Location& Location::operator=(const Location &rhs)
{
// Only do assignment if RHS is a different object from this.
if (this != &rhs)
{
//Copy CArray
m_LocationsToSkip.Copy(rhs.m_LocationsToSkip);
//Copy rest of member variables
//I'd prefer not to do the following
var1 = rhs.var1;
var2 = rhs.var2;
//etc
}
return *this;
}
是的,有點。 使用重載operator=
本身的類型,因此您不必在包含類中執行此操作。 即使在編寫MFC代碼時,我仍然大多使用std::vector
, std::string
等,而不是MFC集合和字符串類。 有時,您幾乎無法使用CString
,但是我不記得上一次使用CArray
而不是std::vector
。
是。 我通常要做的是將除不可復制內容外的所有內容都放在類的Member結構中。 像這樣:
class Location
{
struct Members
{
int var1, var2;
};
Members m;
CArray m_LocationsToSkip;
public:
Location& operator=(Location const& rhs);
};
Location& Location::operator=(const Location &rhs)
{
// Only do assignment if RHS is a different object from this.
if (this != &rhs)
{
//Copy CArray
m_LocationsToSkip.Copy(rhs.m_LocationsToSkip);
//Copy rest of member variables
m = rhs.m; //will use Members automatically generated operator=
//which should do the correct thing because you only put
//normally copyable members in m
}
return *this;
}
我首先在這里發布有關此內容的信息: https : //stackoverflow.com/questions/469696/what-is-your-most-useful-cc-utility/1609496#1609496
不,你不能。 最好的方法是使用腳本生成真實代碼。
通常使用所謂的“復制和交換習慣”來完成。 您實現了一個復制構造函數和一個swap()
方法,該成員交換成員值,最重要的是,交換指向外部數據的指針。 這樣,您的賦值運算符如下所示:
C& C::operator=( const C& c ) {
C tmp( c );
this->swap( tmp );
return *this;
}
您甚至不需要這個的自派保安。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.