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

后端 未结 14 2102
悲哀的现实
悲哀的现实 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 12:06

    As the other answers have pointed out; operator overloading itself isn't necessarily bad. What is bad it when it is used in ways that make the resulting code un-obvious. Generally when using them you need to make them do the least surprising thing (having operator+ do division would cause trouble for a rational class's usage) or as Scott Meyers says:

    Clients already know how types like int behave, so you should strive to have your types behave in the same way whenever reasonable... When in doubt, do as the ints do. (From Effective C++ 3rd Edition item 18)

    Now some people have taken operator overloading to the extreme with things like boost::spirit. At this level you have no idea how it is implemented but it makes an interesting syntax to get what you want done. I'm not sure if this is good or bad. It seems nice, but I haven't used it.

提交回复
热议问题