is the operator '+' unary or binary?

2019-09-21 07:56发布

问题:

While reading this article it seems that the operator + is unary. How is that. From my understanding a unary operator is an operator that does not depend on another variable for its operation like ++a or a-- . How is the variable '+' unary. I thought it was binary ? I would appreciate it if some one could clear this up.

回答1:

+ is both a unary and binary operator. The unary + form (+a) forces the operand to be evaluated as a number or a pointer, while the binary form + form (a + b) is addition.

Unary + is generally the opposite of unary -; applying it to any numeric value will not change it. (+1 == 1) However, it does have some uses, including forcing an array to decay into a pointer:

template <typename T> void foo(const T &) { }

void test() {
    int a[10];

    foo(a);  // Calls foo<int[10]>()
    foo(+a); // Calls foo<int*>()
}

(Demo)

It's the same deal with the - and * operators. You have -a (negation) and a - b (subtraction); *a (pointer dereference) and a * b (multiplication).

You overload both versions differently. For overloading via member functions:

public:
    T operator+() const;          // Unary
    T operator+(const U &) const; // Binary

As with any other operator overload, both forms can return a value different from their enclosing type; for example you might have a string class whose operator+() returns a numeric type. This would be in line with the convention of unary + evaluating its operand as a number.

You can overload these operators as free functions, too:

T operator+(const U &);            // Unary, called on type U and returns T.
T operator+(const U &, const V &); // Binary, called on types U and V and returns T.


回答2:

Unary + as in +a is defined to complement unary - (-a). It is the "default" so actually not often if ever used. However it can be used with variables refering to classes, where it can be overloaded to have a class-specific meaning. So it is not quite entirely useless.