简体   繁体   中英

is the operator '+' unary or binary?

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.

+ 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM