使用重载运算符来实现另一个运算符重载可以吗? [英] Is it okay to use an overloaded operator to implement another operator overload?
问题描述
例如,如果我重载了+运算符
For instance if I have overloaded a + operator
myClass & operator + (const myClass & rhs)
,也重载=运算符
myClass & operator = (const myClass & rhs)
两个操作员都工作正常.我可以在+ =运算符重载中使用此重载运算符吗?
both operators are working fine. Can I use this overloaded operator in my += operator overload?
myClass & operator += (const myClass & rhs){
*this = *this + progA;
return *this;
}
上面的代码可以正常工作.我只想知道这是否是好的代码编写实践,还是应该为+ =运算符重用而重复使用前两个实现中的代码.
The above code is working okay. I just want to know if this is good code writing practice or I should re-use the code from the two previous implementations for the += operator overload.
推荐答案
您可以这样做.但是,更常见的是使用operator+=
而不是其他方法来实现operator+
.
You can do that. However, it is more common to implement operator+
using operator+=
instead of the other way around.
myClass & operator += (const myClass & rhs) { ... )
// Return by value.
// const member function.
myClass operator + (const myClass & rhs) const
{
myClass ret = *this; // Uses copy constructor, not assignment.
return ret += rhs;
}
界面
myClass & operator + (const myClass & rhs);
不是惯用语,因为您不能做到
is not idiomatic since you cannot do the equivalent of
int a = 10 + 20;
使用
MyClass a = MyClass(args...) + MyClass(args...);
由于RHS中的第一个对象是临时对象,因此无法正常工作.
won't work since the first object in RHS is a temporary object.
这篇关于使用重载运算符来实现另一个运算符重载可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!