C++类:在成员函数中创建"this"类的副本

C++ classes: create copy of "this" class within member function

本文关键字:this 副本 创建 函数 成员 C++      更新时间:2023-10-16

我正试图为C++类的+=运算符编写一个函数,该类使用了已编写的+运算符函数。到目前为止,我还没有成功地将this指针与+运算符相关联。这些是我在g++中进行的一些尝试,但没有产生所需的结果。我曾两次尝试简单地复制this类,但似乎都没有成功。

intstr& intstr::operator+=(const intstr& i)
{
  intstr *a;
  a = new intstr;
  *a = *this + i;
  return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
  intstr *a, b(*this);
  a = new intstr;
  *a = b + i;
  return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
  intstr *a, *b;
  a = new intstr;
  b = this;
  *a = *b + i;
  return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
  intstr *a;
  a = new intstr;
  *a = this->operator+(i);
  return *a;
}

在测试代码中,我所做的只是将代码a = a + i的工作行替换为a += i,所以我怀疑问题是否存在,但这是可能的。执行此操作的唯一方法是将代码从+运算符复制到+=函数中吗?

通常方法相反:实现operator+=,然后使用该实现实现operator+(创建第一个参数的副本,然后使用+=递增第二个参数并返回)。

除此之外,为什么在所有版本中都调用new?对于operator+=,您根本不需要创建任何新对象。运算符应通过用右手边的值递增左手边操作数的值来修改该值。无需在任何位置创建新对象(更不用说使用new动态分配了!)

操作员可以看起来像

intstr& intstr::operator+=( const intstr& i )
{
   *this = *this + i;
   return *this;
}

如果operator +被声明为类成员函数,那么您也可以编写

intstr& intstr::operator+=( const intstr& i )
{
   *this = operator +( i ); // or *this = this->operator +( i );  
   return *this;
}

在运算符中动态分配类型为intstr的对象是错误的。至少没有这样的必要。

通常你会用另一种方式:

intstr& intstr::operator+=(intstr const& rhs)
{
     // Do this stuff to add rhs into this object.
     return *this;
}
// Then + is implemented in terms of +=
intstr intstr::operator+(intstr const& rhs)
{
    instr  result(*this);   // Make a copy as the result
    result += rhs;
    return result;
}
// Then your free functions as needed.