C++重载赋值运算符

C++ overloading assignment operator

本文关键字:赋值运算符 重载 C++      更新时间:2023-10-16

我有一个名为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::vectorstd::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;
}

你甚至不需要一个自我分配的警卫。