c++中关于string str="text"+1;编译通过的分析~~~

上述代码在vc10.0和gcc上都能编译通过,输出ext。

这个问题,今天垒代码的时候第一次碰到~~~~当时很惊讶!!

翻了翻c++标准,参考了一下程序结果,大致知道了为什么。

ISO/IEC 14882:2003(E)/ 2.13.4 String literals/ P47:

 

A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes, optionally
beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary
string literal, also referred to as a narrow string literal. An ordinary string literal has type “array of n
const char” and static storage duration (3.7), where n is the size of the string as defined below, and is
initialized with the given characters.

 

标准说的很明白,字符串字面值的类型 是一个const char数组的类型,"text"的类型是 const char[5],数组类型在进行算术运算时,

隐式进行一次Array-to-pointer conversion的标准转换,同时c++标准也明确指出了

 

ISO/IEC 14882:2003(E) /4.2 Array-to-pointer conversion/P88

 

A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type “pointer to
char”; a wide string literal can be converted to an rvalue of type “pointer to wchar_t”. In either case,
the result is a pointer to the first element of the array. This conversion is considered only when there is an
explicit appropriate pointer target type, and not when there is a general need to convert from an lvalue to an
rvalue. [Note: this conversion is deprecated. See Annex D. ] For the purpose of ranking in overload resolution
(13.3.3.1.1), this conversion is considered an array-to-pointer conversion followed by a qualification
conversion (4.4). [Example: "abc" is converted to “pointer to const char” as an array-to-pointer conversion,
and then to “pointer to char” as a qualification conversion. ]

"text"在表达式中转换成一个char  *,然后进行了一次算术运算,最终"text"+1 会返回一个const char *,指向了字符串常量的第2个字符的位置。

然后调用string的转型构造函数生成一个对象。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值