C++ 字符串加字符

cout << ("s" + 'a');

这样一段代码,为什么输出是一个空行呢?
难道是 string literal + character 没有这个运算吗?
没有的话为什么输出是空行呢?

C++ 中, string literal 就是 const char[n] 吗?

阅读 3.7k
1 个回答

表达式"s"的类型是const char[],表达式 'a'的类型是char

数组是不能进行内置加法运算的。所以const char []会被转换成const char *,这里的运算就变成了"指针+整型"(char是一种整型)。输出空行的运行结果实际上是数组越界引起的。

String literal
Narrow multibyte string literal. The type of an unprefixed string literal is const char[]

Additive operators
addition. For the built-in operator, lhs and rhs must be one of the following: Both have arithmetic or unscoped enumeration type. In this case, the usual arithmetic conversions are performed on both operands and determine the type of the result. One is a pointer to complete object type, the other has integral or unscoped enumeration type. In this case, the result type has the type of the pointer

Array-to-pointer decay
There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题