首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++关于string的小疑点

2012-09-23 
c++关于string的小问题1.conststd::stringhelloHello conststd::stringmessagehello+,world +!

c++关于string的小问题
  1.   const   std::string   hello   =   "Hello ";
        const   std::string   message   =   hello   +   ",   world "   +   "! ";
   
  2.   const   std::string   exclam   =   "! ";
        const   std::string   message   =   "Hello "   +   ",   world "   +   exclam;


      为什么第一个可以运行,而第二个就不可以,是错误的,求解释,菜鸟一只



[解决办法]
看看string的+操作符重载
[解决办法]
const std::string message = hello + ", world " + "! "; 

hello + ", world " = string + char* = operator+( string, string(char*) )
char* 被提升到string,然后相加返回一个string



const std::string message = "Hello " + ", world " + exclam;
"Hello " + ", world " = char* + char* //错误,没有指针间不可能相加
[解决办法]
因为+运算符是左结合的。
 hello + ", world " + "! "
相当于
(hello + ", world ") + "! "
每一步运算都有意义,因为string + const char*有意义而且返回一个string

"Hello " + ", world " + exclam
则相当于
("Hello " + ", world ") + exclam
这里两个指针相加无意义,因此无法通过编译
[解决办法]
顶一个

探讨

因为+运算符是左结合的。
hello + ", world " + "! "
相当于
(hello + ", world ") + "! "
每一步运算都有意义,因为string + const char*有意义而且返回一个string

"Hello " + ", world " + exclam
则相当于
("Hello " +……

热点排行