前言
在使用C++中的字符串时,习惯性的把两个使用""括起来的字符串使用+连接,结果报错error: invalid operands of types 'const char [6]' and 'const char [6]' to binary 'operator+'
意思是对两个const char*类型的操作数进行+运算是非法的,本来想着两个字符串能够像c++中的string一样进行连接,结果与自己想的大相径庭。
一、发生的场景

//std::string str = "hello" + "world"; // error: invalid operands of types 'const char [6]' and 'const char [6]' to binary 'operator+'
//std::string str = std::string("hello") + " world"; // 正确
//std::string str = "hello" + std::string("world"); //正确
std::string str = "hello"" world"; //正确
cout << "str=" << str << endl;
使用+运算符连接两个使用""包裹的字符串时报错。原因是在C++中,""括起来的字符串被当成是const char*类型,而非string类型。
二、解决方法
参考stackoverflow上的解释,详细内容请阅读error: invalid operands of types ‘const char*’ and ‘const char*’ to binary ‘operator+’
1.显式声明其中一个为std::string类型(推荐写法)
std::string str = std::string("hello") + " world";
2.去掉+,让编译器拼接字符串(不推荐)
std::string str = "hello"" world";
大多数编译器会自动拼接""包围的字符串,但不保证所有的编译器都正常。推荐显示声明为string类型的字符串再进行+操作。
三、验证
std::string str1 = std::string("hello") + " world" + "!"; // 正确
std::string str2 = "hello" + std::string(" world") + "!"; //正确
std::string str3 = "hello"" world" "!"; //正确
cout << "str1=" << str1 << endl;
cout << "str2=" << str2 << endl;
cout << "str3=" << str3 << endl;

本文介绍了在C++中尝试使用+运算符连接两个const char*类型字符串时遇到的错误,即`invalid operand of types 'const char[6]' and 'const char[6]' to binary 'operator+'`。错误发生的原因是C++将双引号包围的字符串视为const char*类型,而不是std::string。解决方法包括显式将其中一个转换为std::string类型或者利用编译器的字符串字面量连接特性。文章提供了验证不同连接方式的正确示例。

2000

被折叠的 条评论
为什么被折叠?



