一元加运算符对char数组的目的是什么? [英] What is the purpose of unary plus operator on char array?

查看:165
本文介绍了一元加运算符对char数组的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What does the following do? I thought + was for integer promotion only.

char c[20] = "hello";
foo(+c);
foo(+"hello");


推荐答案

强制数组衰减为指针间接说明在§5.3.1[expr.unary.op] / 7:

It forces the array to decay to a pointer, as indirectly stated in §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.

你可能不会看到它,数组不是列出的类型之一,它必须转换为指针以适合。

You might not see it at first, but since an array is not one of the types listed, it must be converted to a pointer in order to fit. From there, the value of the pointer is returned.

在这两种情况下, foo(const char *)将被选择 foo(const char(&)[N])。有关可以使用一元加号的有用事例的示例,请参见此答案。包括将枚举类型转换为整数并解决链接问题。正如你所说,它也可以用于整体推广。例如, unsigned char byte = getByte(); std :: cout<

In both cases, a foo(const char *) would be chosen over a foo(const char(&)[N]). For some examples of useful things you can use unary plus for, see this answer. Included are converting an enum type to an integer and getting around a linking issue. As you say, it can also be used for integral promotion. For example, unsigned char byte = getByte(); std::cout << +byte; will print the numerical value and never the character.

一个简单的例子是: :

A straightforward example is:

char a[42];
cout << sizeof(a) << endl;  // prints 42
cout << sizeof(+a) << endl; // prints 4

这篇关于一元加运算符对char数组的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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