C++ multiple operator overloads for the same operator

前端 未结 3 1936
星月不相逢
星月不相逢 2021-02-14 04:14

I know I can answer this question easily for myself by generatin the code and see if it compiles. But since I couldn\'t find a similar question, I thought it\'s knowledge worth

3条回答
  •  天命终不由人
    2021-02-14 04:57

    The canonical form of implementing operator+() is a free function based on operator+=(), which your users will expect when you have +. += changes its left-hand argument and should thus be a member. The + treats its arguments symmetrically, and should thus be a free function.

    Something like this should do:

    //Beware, brain-compiled code ahead!
    class MyClass {
    public:
        MyClass& operator+=(const MyClass &rhs) const
        {
          // code for adding MyClass to MyClass
          return *this;
        }
        MyClass& operator+=(int rhs) const
        {
          // code for adding int to MyClass
          return *this;
        }
    };
    
    
    inline MyClass operator+(MyClass lhs, const MyClass& rhs) {
      lhs += rhs;
      return lhs;
    }
    inline MyClass operator+(MyClass lhs, int rhs) {
      lhs += rhs;
      return lhs;
    }
    // maybe you need this one, too
    inline MyClass operator+(int lhs, const MyClass& rhs) {
      return rhs + lhs; // addition should be commutative
    }
    

    (Note that member functions defined with their class' definition are implicitly inline. Also note, that within MyClass, the prefix MyClass:: is either not needed or even wrong.)

提交回复
热议问题