C++类:在成员函数中创建"this"类的副本
C++ classes: create copy of "this" class within member function
我正试图为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.
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- 用callgrind追踪不必要的副本
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 关于C++中具有多重继承"this"指针的说明
- 检查注册表项是否链接到(或副本)另一个注册表项
- 在noexcept 规范中是否允许使用"this"?
- 如何修复"error: ‘_1’ was not declared in this scope"?
- 为什么构建目录中新构建的共享库与安装目录中的副本具有不同的依赖项集?
- C++调用具有 *this 属性的单个帮助程序函数
- Doees the 'this' 指针参与虚函数的多态行为
- C++基于范围的 for 循环和元素副本
- 在 c++ 中正确定义"this"关键字?
- 创建提升::shared_ptr的深层副本
- C++类:在成员函数中创建"this"类的副本
- 为什么static_cast(*this)到基类会创建一个临时副本