Is it okay to use an overloaded operator to implement another operator overload?

旧城冷巷雨未停 提交于 2020-01-14 17:51:26

问题


For instance if I have overloaded a + operator

myClass & operator + (const myClass & rhs)

and also overloaded = operator

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.


回答1:


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;
}

The interface

myClass & operator + (const myClass & rhs);

is not idiomatic since you cannot do the equivalent of

int a = 10 + 20;

Using

MyClass a = MyClass(args...) + MyClass(args...);

won't work since the first object in RHS is a temporary object.



来源:https://stackoverflow.com/questions/49657351/is-it-okay-to-use-an-overloaded-operator-to-implement-another-operator-overload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!