现在的位置: 首页 > 综合 > 正文

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

2018年07月05日 ⁄ 综合 ⁄ 共 1858字 ⁄ 字号 评论关闭

上述代码在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的转型构造函数生成一个对象。

 

抱歉!评论已关闭.