Tuesday 7 January 2020

C++: Why is 'operator+=' defined but not 'operator+' for strings?




How come operator+= is defined for std::string but operator+ is not defined? See my MWE below (http://ideone.com/OWQsJk).



#include 

#include
using namespace std;

int main() {
string first;
first = "Day";
first += "number";
cout << "\nfirst = " << first << endl;

string second;

//second = "abc" + "def"; // This won't compile
cout << "\nsecond = " << second << endl;
return 0;
}

Answer



You need to convert one of the raw string literals to std::string explicitly. You can do it like others already mentioned:



second = std::string("abc") + "def";



or with C++14, you will be able to use



using namespace std::literals;
second = "abc"s + "def";
// note ^

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...