Comparing objects using bool operator==

前端 未结 4 1482
说谎
说谎 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:47

    The biggest problem I see with virtual bool operator==( BaseClass const &right ) is that, without multiple dynamic dispatch*, the following assertion will fail.

    class Derived1 : public BaseClass {
        bool operator==( BaseClass const &right ) override {
            return true;
        }
    }
    
    class Derived2 : public BaseClass {
        bool operator==( BaseClass const &right ) override {
            return false;
        }
    }
    
    Derived1 d1;
    Derived2 d2;
    assert((d1 == d2) == (d2 == d1));
    

    The friend function can be made to handle this, but to be honest, it's a lot of trouble to get something like this right without multiple dispatch. Even with multiple dispatch, proper semantics for such a polymorphic equality operator may not be easy to come up with.


    * multiple dynamic dispatch is the ability to do dynamic dispatch on more than one argument, instead of just on this.

提交回复
热议问题