LxL*_*LxL 4 c++ operator-overloading
以这种方式定义operator + =是对的吗?
void operator +=(const BigNumber& other)
{
*this=(*this) + other;
}
Run Code Online (Sandbox Code Playgroud)
在这样的类:
class BigNumber
{
public:
//....
BigNumber operator +(const BigNumber& other)
{
return sum(other);
}
//....
}
Run Code Online (Sandbox Code Playgroud)
是.但正确的方法是实施以下operator+方面operator+=:
struct foo
{
int value;
foo& operator+=( const foo& other )
{
value += foo.value;
return *this ;
}
friend foo operator+( foo lhs , const foo& rhs )
{
return lhs += rhs;
}
};
Run Code Online (Sandbox Code Playgroud)
首先,operator+()不应将二进制文件定义为成员函数而不是自由函数.这允许您在第一个参数不是a的情况下实现添加foo.常见的习惯用法是friend在类中声明它以克服封装.
其次,这种方式提供了连贯,可维护和有效的界面.
如果您实现+=操作,则用户进行操作(除极少数情况外)该类型也提供二进制加法.实现+与+=提供这确保了两个操作的行为是一致的.
您已经实现了+使用+=,因此真正执行添加的代码只写入一次.如果您将来需要更改操作,则必须仅更改一个代码,如果它有错误,则该错误仅在一个站点中.一般来说,减少代码重复是一种很好的做法.
operator+()编写的方式允许编译器轻松地删除副本,从而提高二进制加法的性能.
使用的习语是"复制第一个操作数,对其进行操作,返回副本".因此编译器可以轻松执行返回值优化(RVO).此外,它通过值传递第一个操作数,而不是在函数内手动复制操作数.这允许编译器在第一个操作数是rvalue时执行更多的复制精简(让编译器决定何时以及如何复制).
| 归档时间: |
|
| 查看次数: |
215 次 |
| 最近记录: |