C++重载赋值运算符
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
是什么时候了。
是。我通常所做的是将所有内容都放在类的Members结构中,除了不可复制的内容。像这样:
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-c-c-utility/1609496#1609496
不,你不能。最好的方法是使用脚本生成真实的代码。
这通常使用所谓的"复制和交换习惯用法"来完成。您实现了一个复制构造函数和一个swap()
方法,该方法交换成员值,最重要的是,还交换指向外部数据的指针。这样一来,你的任务操作员看起来像:
C& C::operator=( const C& c ) {
C tmp( c );
this->swap( tmp );
return *this;
}
你甚至不需要一个自我分配的警卫。
相关文章:
- 使用赋值运算符重载从类中返回jobject
- 赋值运算符重载和自赋值
- C++ 指针赋值运算符重载(不仅是对象赋值,还有指针赋值)
- 赋值运算符重载在通过指针访问时不调用
- "return *this"赋值运算符重载
- 赋值运算符重载 c++ 的返回值
- 在对类对象的赋值进行链接时获取垃圾值,使用按值返回类对象的赋值运算符重载
- 在c++中的赋值运算符重载方法中删除旧的动态分配内存
- 复合赋值运算符重载
- 对象的动态内存和赋值运算符重载
- c++中的赋值运算符重载
- c++赋值运算符重载
- 如何通过赋值运算符重载将一个列表复制到另一个列表上?C++
- 赋值运算符重载和无效内存
- 赋值运算符重载 -- 错误 C2440:'==':无法从 'A<T> *' 转换为 'A<T> *const '
- 为什么内存泄漏只发生在赋值运算符重载的情况下,而不是在复制构造函数中,以及复制和交换习惯用法如何解决它
- 内存泄漏,使赋值运算符重载、新建、删除和C++
- C++中的效率和赋值运算符重载
- 赋值运算符重载/检索功能
- 为什么在赋值运算符重载中返回引用