c++ - 是否可以为 C++ +'s string class? And to concatenate "文字创建运算符函数?

标签 c++ string concatenation

我可以为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::strings 中,则以下 有效:

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/

相关文章:

c - 在 C 中将常量添加到变量名

c - 删除最后一个字符,然后连接两个字符串

c++ - pthreads 编译但未创建二进制文件

Java,按标点符号分割字符串,处理字符串,将标点符号添加回字符串

c++ - 如何在 C++ 中连接函数 m_stream 中的字符串?

python - 保留包含在其他数据框中的数据框的值

python - 如何在 Python 中执行包含 Python 代码的字符串?

c++ - 在 DLL 中导出的 C++ 函数中使用 #ifdef block

c++ - 模板函数中 const 引用的类型推导

c++ - 使用 gnuPlot 在 C++ 中绘制图形