就C++来说,operator+、operator=和operator+=之间没有任何关系,因此如果你想让这三个operator同时存在并具有你所期望的关系,就必须自己实现它们。同理,operator -, *, /, 等等也一样。
template<class T>
const T operator+(const T& lhs, const T& rhs)
{ return T(lhs) += rhs; }
表达式T(lhs)调用了T的拷贝构造函数。它建立一个临时对象,其值与lhs一样。这个临时对象用来与rhs一起调用operator+= ,操作的结果被从operator+返回。这个代码好像不用写得这么隐密。这样写不是更好么?
template<class T>
const T operator+(const T& lhs, const T& rhs)
{
T result(lhs); // 拷贝lhs 到 result中
return result += rhs; // rhs与它相加并返回结果
}
operator的赋值形式(operator+=)比单独形式(operator+)效率更高。做为一个库程序设计者,应该两者都提供,做为一个应用程序的开发者,在优先考虑性能时你应该考虑考虑用operator赋值形式代替单独形式。
本文探讨了C++中operator+、operator=和operator+=的实现方式及其性能考量。通过对比不同实现方法,强调了operator赋值形式相较于单独形式的优势,并提供了具体的代码示例。
172

被折叠的 条评论
为什么被折叠?



