Number of arguments in operator overload in C++

前端 未结 5 1472
梦如初夏
梦如初夏 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:59

    If you prefer that operator+ takes both operands as explicit arguments, it must be defined as a free (i.e. non-member) function:

    class Complex {
        friend Complex operator+(const Complex& lhs, const Complex& rhs);
    }
    
    Complex operator+(const Complex& lhs, const Complex& rhs) {
        ...
    }
    

    You have to use this form if the left operand is of a primitive type, or of a class that you don't control (and thus can't add a member function to).

提交回复
热议问题