difference between global operator and member operator

前端 未结 5 721
一整个雨季
一整个雨季 2020-12-02 12:43

Is there a difference between defining a global operator that takes two references for a class and defining a member operator that takes only the right operand?

Glob

5条回答
  •  忘掉有多难
    2020-12-02 12:46

    Your smartest option is to make it a friend function.

    As JaredPar mentions, the global implementation cannot access protected and private class members, but there's a problem with the member function too.

    C++ will allow implicit conversions of function parameters, but not an implicit conversion of this.

    If types exist that can be converted to your X class:

    class Y
    {
    public:
        operator X();  // Y objects may be converted to X
    };
    
    
    X x1, x2;
    Y y1, y2;
    

    Only some of the following expressions will compile with a member function.

    x1 == x2;   // Compiles with both implementations
    x1 == y1;   // Compiles with both implementations
    y1 == x1;   // ERROR!  Member function can't convert this to type X
    y1 == y2;   // ERROR!  Member function can't convert this to type X
    

    The solution, to get the best of both worlds, is to implement this as a friend:

    class X
    {
        int value;
    
    public:
    
        friend bool operator==( X& left, X& right ) 
        {
            return left.value == right.value;
        };
    };
    

提交回复
热议问题