运算符'+'是一元还是二元?

Mis*_*tyD -1 c++ operator-overloading

在阅读文章似乎运营商+是一元的.那个怎么样.根据我的理解,一元运算符是一个运算符,它不依赖于另一个变量来操作,如++ a或a--.变量'+'是如何一元的.我以为是二进制?如果有人能清楚这一点,我将不胜感激.

cdh*_*wie 6

+既是一元和二元运算符.一元+form(+a)强制操作数被计算为数字或指针,而二进制形式+form(a + b)是加法.

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

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

void test() {
    int a[10];

    foo(a);  // Calls foo<int[10]>()
    foo(+a); // Calls foo<int*>()
}
Run Code Online (Sandbox Code Playgroud)

(演示)

-*运营商的处理方式相同.你有-a(否定)和a - b(减法); *a(指针取消引用)和a * b(乘法).

您以不同方式重载两个版本 对于通过成员函数重载:

public:
    T operator+() const;          // Unary
    T operator+(const U &) const; // Binary
Run Code Online (Sandbox Code Playgroud)

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

您也可以将这些运算符作为自由函数重载:

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.
Run Code Online (Sandbox Code Playgroud)