以下是做什么的?我认为 + 仅用于整数提升。
char c[20] = "hello";
foo(+c);
foo(+"hello");
最佳答案
它强制数组衰减为指针,如 §5.3.1 [expr.unary.op]/7 中间接说明的:
The operand of the unary + operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument. Integral promotion is performed on integral or enumeration operands. The type of the result is the type of the promoted operand.
您可能一开始看不到它,但由于数组不是列出的类型之一,因此必须将其转换为指针才能适应。从那里返回指针的值。
在这两种情况下,foo(const char *)
将被选择而不是 foo(const char(&)[N])
.有关可以使用一元加号的有用事物的一些示例,请参阅 this answer .包括将枚举类型转换为整数并解决链接问题。正如你所说,它也可以用于积分促销。例如,unsigned char byte = getByte(); std::cout << +byte;
将打印数值而不是字符。
一个简单的例子是:
char a[42];
cout << sizeof(a) << endl; // prints 42
cout << sizeof(+a) << endl; // prints 4
关于c++ - char数组上的一元加运算符的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701381/