在c++中,我通过+对字符串进行了拼接,然后cout输出这个字符串的时候我使用cout<<str+"helloworld";但是输出的结果不是应该输出的结果,str丢失了,但是我通过cout<<str<<"helloworld";输出确实正常的,我想问这种情况是什么原因?(偶然事件,但是出现几率不是0)
首先,std::cout 不支持 std::string 作为右操作数。需要转换为 const char* 即:str.c_str(),所以,代码应如下:
std::string str = "foo";
str += " bar";
std::cout << str.c_str() << std::endl;
学会调试,看看运行时刻str到底是什么?