是否可以为C++的字符串类创建一个operator +函数?并连接"文字"?

tru*_*ktr 6 c++ string concatenation

我可以随意operator+()为C++的string类编写一个函数,所以我不必<sstream>用来连接字符串吗?

例如,而不是做

someVariable << "concatenate" << " this";
Run Code Online (Sandbox Code Playgroud)

operator+()我可以添加一个,这样我就能做到

someVariable = "concatenate" + " this";
Run Code Online (Sandbox Code Playgroud)

Aus*_*oke 15

std::string operator+ 确实连接了两个std::string.然而,你的问题是,"concatenate""this"不是两个std::string; 他们是类型const char [].

如果你想连接两个文字"concatenate","this"无论出于什么原因(通常你可以在多行上拆分字符串),你可以:

string someVariable = "concatenate" " this";
Run Code Online (Sandbox Code Playgroud)

编译器会意识到你真正想要的 string someVariable = "concatenate this";


如果"concatenate""this"存储在std::strings中,则以下内容有效:

string s1 = "concatenate";
string s2 = " this";

string someVariable = s1 + s2;
Run Code Online (Sandbox Code Playgroud)

要么

string s1 = "concatenate";

string someVariable = s1 + " this";
Run Code Online (Sandbox Code Playgroud)

甚至

string someVariable = string("concatenate") + " this";
Run Code Online (Sandbox Code Playgroud)

在调用时" this"将自动转换std::string对象的operator+位置.要进行此转换,至少有一个操作数必须是类型std::string.