我可以为C++的string
类任意写一个operator+()
函数,这样我就不用
连接了字符串?
例如,而不是做
someVariable << "concatenate" << " this";
我可以添加一个 operator+()
这样我就可以了
someVariable = "concatenate" + " this";
?
最佳答案
std::string
operator+
确实 连接两个 std::string
。但是,您的问题是 "concatenate"
和 "this"
不是两个 std::string
;它们的类型是 const char []
。
如果您想连接两个文字 "concatenate"
和 "this"
出于任何原因(通常这样您可以将字符串拆分为多行),您可以这样做:
string someVariable = "concatenate" " this";
编译器会意识到你实际上想要 string someVariable = "concatenate this";
如果 "concatenate"
和 "this"
存储在 std::string
s 中,则以下 是 有效:
string s1 = "concatenate";
string s2 = " this";
string someVariable = s1 + s2;
或
string s1 = "concatenate";
string someVariable = s1 + " this";
甚至
string someVariable = string("concatenate") + " this";
"this"
会在 operator+
被调用时自动转换成一个std::string
对象.要进行此转换,至少有一个操作数必须为 std::string
类型。
关于c++ - 是否可以为 C++ +'s string class? And to concatenate "文字创建运算符函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8003961/