【问题标题】:C++ classes: create copy of "this" class within member functionC++ 类:在成员函数中创建“this”类的副本
【发布时间】:2014-10-17 04:10:55
【问题描述】:

我正在尝试为 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,所以我怀疑问题出在哪里,但有可能。是否只有将代码从 + 运算符复制到 += 函数中?

【问题讨论】:

标签: c++ class operator-keyword


【解决方案1】:

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

除此之外,您为什么在所有版本中都调用new?对于operator+=,您根本不需要创建任何新对象。操作员应该修改左侧操作数的值,增加右侧的值。无需在任何地方创建新对象(使用new 动态分配的对象更少!)

【讨论】:

  • 感谢您的快速回复!起初,我不认为我需要“新”,但直到我使用它,我的代码才被编译,所以我就照做了。我从没想过首先使用“+=”并从中派生“+”——很高兴知道!我会试试的。
【解决方案2】:

操作符可以是这样的

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 类型的对象是错误的。至少没有必要这样做。

【讨论】:

  • 谢谢,这成功了!我知道必须有一种简单的方法来做到这一点。
  • @Vlad 如果我们使用 return ( operator + ( i )); 也可以吗? ?
  • @sameer karjatkar 不,不会的。运算符 + 可能不会更改左操作数。它可能会返回一个临时对象,甚至是一个 const 临时对象。
【解决方案3】:

通常你会反其道而行之:

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.

【讨论】:

  • 我不确定..你不认为结果对象会在操作符函数结束时被销毁吗?
  • @sameerkarjatkar:不,它将按值返回。请记住 operator+ 创建一个新值,您按值返回以将其从函数中取出。
猜你喜欢
  • 2017-11-29
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
  • 2017-01-24
相关资源
最近更新 更多