运算符"+"是一元还是二进制? [英] is the operator '+' unary or binary?

查看:236
本文介绍了运算符"+"是一元还是二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读这篇文章时,似乎运算符+是一元的.那个怎么样. 据我了解,一元运算符是一种不依赖于另一个变量(例如++ a或a--)进行运算的运算符.变量"+"如何一元.我以为是二进制的?如果有人能解决这个问题,我将不胜感激.

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.

推荐答案

+既是一元运算符,又是二进制运算符.一元+形式(+a)强制将操作数评估为数字或指针,而二进制形式+形式(a + b)是加法运算.

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

一元+通常与一元-相反.将其应用于任何数值将不会更改它. (+1 == 1)但是,它确实有一些用途,包括强制将数组衰减为指针:

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*>()
}

(演示)

-*运算符相同.您有-a(取反)和a - b(减法); *a(指针取消引用)和a * b(乘法).

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

与其他任何运算符重载一样,两种形式都可以返回与其封闭类型不同的值;例如,您可能有一个字符串类,其operator+()返回数字类型.这符合一元+将其操作数评估为数字的约定.

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.

这篇关于运算符"+"是一元还是二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆