Comparing objects using bool operator==

前端 未结 4 1492
说谎
说谎 2021-02-14 05:04

So, after reading some SO questions and answers, i still doesn\'t understand why use

friend bool operator==( BaseClass const &left, BaseClass const &righ         


        
4条回答
  •  爱一瞬间的悲伤
    2021-02-14 05:51

    There are two independent points you are trying to make. Firstly, implementing operator as a member function instead of a standalone function. Secondly, implementing it as a virtual function (you even put in in the title).

    What are you trying to say by the "virtual" part is not clear. In your code sample the derived class operator does not override base class operator, because their signatures do not match. There's no polymorphism in your example. So, I don't understand what you mean by staying that it "works fine". It doesn't really work at all (as "virtual" operator), since in your code there's really nothing that can "work" yet. At the current moment your code merely compiles, but it doesn't do anything. Provide code that would attempt to demonstrate polymorphic behavior - then we'll see whether it is "working" or not.

    As for implementing binary operators as member functions... This matter has been covered more than once already. Binary operators implemented as member functions behave "asymmetrically" with regard to implicit argument conversions. Which is why it is usually a better idea to implement symmetrical binary operators as standalone functions.

提交回复
热议问题