c++中关于string str="text"+1;编译通过的分析~~~
来源:互联网 发布:wp采集软件 编辑:程序博客网 时间:2024/05/16 11:20
上述代码在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的转型构造函数生成一个对象。
- c++中关于string str="text"+1;编译通过的分析~~~
- String str = null、String str = ""、String str = new String()中所声明对象str之间的区别:
- C++string str="abc";sizeof(str)
- 关于String str =new String("abc")和 String str = "abc"的比较
- 关于String str = new String("abc")的详解
- 关于String str="abc"
- 关于String str="abc"
- Delphi中定义为string的变量str头元素是str[0]还是str[1]?
- C#中String str与String str=“”的区别 及 函数的参数数组。
- java关于String[] str = new String[]{};
- 在C#中,string str = null 与 string str = “” 请尽量使用文字或图象说明其中的区别。
- String str = "str"和String str = new String("str")的区别
- C++(<string>):string str="xxxx"+"6";
- String str="a" 的内存存储情况分析
- 关于string.equals("str")的小技巧
- string str = null 与 string str =""的区别
- c++ string c.str()的用法
- string 中 str.assign() 的用法
- Windows Socket五种I/O模型——代码全攻略
- 大二了
- 基于mes的车间质量管理系统设计与实现
- 大二了
- 使用gdb、gdbserver在ARM-Linux下进行远程调试
- c++中关于string str="text"+1;编译通过的分析~~~
- 防止java反编译的一些常用方法
- Silverlight + WCF错误“The remote server returned an error: NotFound.”的解决方法
- Axis Web Service开发之旅 (六) --会话(Session)管理
- asterisk 杂事记录
- 揭开Socket编程的面纱
- 关于软件开发中兼容win7注册表的若干思考
- zoj1694_Shredding Company
- WinCE 背光显示bug