[英]Overload += operator as friend function
I read that implementing operators as friend function will be better. 我读到将运算符实现为朋友功能会更好。 How to overload += operator as a friend function when I already have + operator function: 当我已经拥有+运算符功能时,如何将+ =运算符作为朋友函数重载:
friend Dollar operator+(const Dollar &p1, const Dollar &p2);
friend Dollar &operator+=(const Dollar &p1, const Dollar &p2);
This is wrong since I need to return a reference to a variable. 这是错误的,因为我需要返回对变量的引用。
Dollar &operator+=(const Dollar &p1, const Dollar &p2)
{
return p1+p2;
}
Overloading operators as friend functions is better in order to allow conversions to apply to both the left and right side of the expression. 重载运算符作为朋友函数更好,以便允许将转换应用于表达式的左侧和右侧。 For example, string
's operator+
is a friend so that I can write "Hello " + string("World")
rather than only being able to write string("Hello ") + "World"
. 例如, string
的operator+
是一个朋友,因此我可以写"Hello " + string("World")
而不是只能写string("Hello ") + "World"
。
However, this reasoning doesn't apply to mutators such as operator+=
. 但是,这种推理不适用于诸如operator+=
变异器。 You have to take a non-const left argument, which precludes being able to use this operator on a temporary. 您必须采用非常量left参数,这排除了可以在临时位置使用此运算符的可能性。 For this reason, it's recommended to implement non-mutating operators as friend
(or otherwise free-) functions and mutators as member functions. 因此,建议将非变异算子实现为friend
(或其他自由函数)功能,并将变异器实现为成员函数。 (In fact, operator=
can only be overloaded as a member function.) (实际上,只能将operator=
作为成员函数重载。)
You also need to modify the lvalue. 您还需要修改左值。
Dollar &operator+=(Dollar &p1, const Dollar &p2)
{
p1=p1+p2;
return p1;
}
通常的方法是提供+=
作为修改*this
的成员函数,并将+
实现为使用+=
的自由函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.