Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

#include <iostream>
#include <string>
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;
}
like image 262
jlconlin Avatar asked Jul 09 '14 17:07

jlconlin


2 Answers

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       ^
like image 160
Daniel Frey Avatar answered Oct 30 '22 12:10

Daniel Frey


Those aren't std::strings, they are const char *. Try this:

 second = std::string("abc") + "def";
like image 31
eduffy Avatar answered Oct 30 '22 12:10

eduffy