C++: Why is 'operator+=' defined but not 'operator+' for strings?
本问题已经有最佳答案,请猛点这里访问。
为什么
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> #include <string> using namespace std; int main() { string first; first ="Day"; first +="number"; cout <<" first =" << first << endl; string second; //second ="abc" +"def"; // This won't compile cout <<" second =" << second << endl; return 0; } |
您需要将一个原始字符串文本显式转换为
1 | second = std::string("abc") +"def"; |
或者用C++ 14,你就可以使用
1 2 3 | using namespace std::literals; second ="abc"s +"def"; // note ^ |
那些不是
1 | second = std::string("abc") +"def"; |
C++: Why is 'operator+=' defined but not 'operator+' for strings?
它是。它要求至少有一个操作数是
1 2 3 4 5 6 7 | int main() { std::string foo("foo"); std::string bar("bar"); std::string foobar = foo + bar; std::cout << foobar << std::endl; } |
在您的案例中,问题是您试图添加字符串文本
只有当至少一个操作数的类型为
在