c++ - char数组上的一元加运算符的目的是什么?

标签 c++

以下是做什么的?我认为 + 仅用于整数提升。

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/

相关文章:

c++ - 如果atomic_compare_exchange在它自己的线程上不是原子的,它如何实现锁?

c++ - 多项式类在调试器中运行良好,但在尝试构建和运行时却不行

c++ - 将utf16宽std::wstring转换为utf8窄std::string以获得稀有字符时的问题

c++ - 写文件过程崩溃!关闭

c++ - 如何从 gcc 内联 arm7 程序集调用 c++ 成员函数

c++ - C++ std::map 中的 "Uninitialised value was created by a stack allocation"

c++ - IFTResult 到 cvMat 像素坐标

c++ - 无法使用 cmake 构建 Opencv 项目

C++:初始化指向 int 的指针

c++ - 如何只传递一些默认参数?