What makes Scala's operator overloading “good”, but C++'s “bad”?

后端 未结 14 2105
悲哀的现实
悲哀的现实 2020-12-12 11:20

Operator overloading in C++ is considered by many to be A Bad Thing(tm), and a mistake not to be repeated in newer languages. Certainly, it was one feature specifically drop

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 11:41

    In general it is not a bad thing.
    New languages such as C# also have operator overloading.

    It is the abuse of operator overloading that is a bad thing.

    But there are also problems with operator overloading as defined in C++. Because overloaded operators are just syntactic sugar for method calls they behave just like method. On the other hand normal built-in operators do not behave like methods. These inconsistency can be cause problems.

    Off the top of my head operators || and &&.
    The built in versions of these are short-cut operators. This is not true for overloaded versions and has caused some problems.

    The fact that + - * / all return the same type that they operate on (after operator promotion)
    The overloaded versions can return anything (This is where the abuse sets in, If your operators start to return some arbitrator type the user was not expecting things go down hill).

提交回复
热议问题