Number of arguments in operator overload in C++

前端 未结 5 1575
梦如初夏
梦如初夏 2021-01-31 04:09

I\'m learning C++ and I created two simple hello-world applications. In both of them I use operator overload, but here is the problem. On the first one, I can provide two argume

5条回答
  •  逝去的感伤
    2021-01-31 04:55

    Suppose you have a class like this:

    class Element {
    public:
        Element(int value) : value(value) {}
        int getValue() const { return value; }
    private:
        int value;
    };
    

    There are four ways to define a binary operator such as +.

    1. As a free function with access to only the public members of the class:

      // Left operand is 'a'; right is 'b'.
      Element operator+(const Element& a, const Element& b) {
          return Element(a.getValue() + b.getValue());
      }
      

      e1 + e2 == operator+(e1, e2)

    2. As a member function, with access to all members of the class:

      class Element {
      public:
          // Left operand is 'this'; right is 'other'.
          Element operator+(const Element& other) const {
              return Element(value + other.value);
          }
          // ...
      };
      

      e1 + e2 == e1.operator+(e2)

    3. As a friend function, with access to all members of the class:

      class Element {
      public:
          // Left operand is 'a'; right is 'b'.
          friend Element operator+(const Element& a, const Element& b) {
              return a.value + b.value;
          }
          // ...
      };
      

      e1 + e2 == operator+(e1, e2)

    4. As a friend function defined outside the class body—identical in behaviour to #3:

      class Element {
      public:
          friend Element operator+(const Element&, const Element&);
          // ...
      };
      
      Element operator+(const Element& a, const Element& b) {
          return a.value + b.value;
      }
      

      e1 + e2 == operator+(e1, e2)

提交回复
热议问题