+ -ing字符串和<< - 字符串在c ++中有什么区别吗?

108*_*108 2 c++ text cout concatenation

如果以下片段的效果之间存在差异,则有什么区别:

cout << "Some text" << s1 << "some more text\n";

cout << "Some text" + s1 + "some more text\n";
Run Code Online (Sandbox Code Playgroud)

E.M*_*.M. 15

operator + on strings的结果是一个新字符串.因此,在示例中

cout << "Some text" + s1 + "some more text\n";
Run Code Online (Sandbox Code Playgroud)

在将整个事物写入cout之前,会创建两个新字符串(暗示内存分配).在您的第一个示例中,所有内容都直接写入cout而没有不必要的内存分配.


Mar*_*som 5

考虑以下:

cout << "Some text" + " " + "some more text\n";
Run Code Online (Sandbox Code Playgroud)

它不会做你的想法.运算符+并不总是意味着连接.

编辑:当应用于原始字符串时,operator +不会连接 - 它会将指针的地址添加到字符串中.结果几乎可以保证是无意义的,因为它指向与任何原始字符串无关的内存区域.运气好的话会让你的程序崩溃.

编辑2:显然,自从我犯了这个错误以来已经很长时间了.结果是如此荒谬,编译器拒绝编译它.