7

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;
}
jlconlin
  • 14,206
  • 22
  • 72
  • 105

4 Answers4

10

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       ^
Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
6

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

 second = std::string("abc") + "def";
eduffy
  • 39,140
  • 13
  • 95
  • 92
  • 2
    Technically they're not `const char*`, they're `const char[4]`. – Mooing Duck Jul 09 '14 at 17:26
  • @MooingDuck And non-technically too :-) – juanchopanza Jul 09 '14 at 17:27
  • 1
    @MooingDuck Technically technically they're `const char (&)[4]`. – David G Jul 09 '14 at 17:28
  • @0x499602D2: I almost typed that, but I then assumed that literals are not references, they are values. Tested just now, it does indeed bind to a mutable reference, so I guess you're right that they're references: http://coliru.stacked-crooked.com/a/b60f5bc56c82e568. Actually, maybe they're just lvalues? I dunno. – Mooing Duck Jul 09 '14 at 17:36
  • @MooingDuck No, it's still a reference. [See this.](http://stackoverflow.com/questions/15047277/what-is-the-result-of-decltypehello) :) – David G Jul 09 '14 at 17:40
  • 3
    @0x499602D2 From your link: "The type of a string literal is changed... to array of const char." "if `e` is an lvalue, `decltype(e)` is `T&`, where `T` is the type of `e`;" That's pretty clear that the type of `e` is `T` and NOT a reference. `decltype("literal")` is a reference, but `"literal"` is merely an lvalue. – Mooing Duck Jul 09 '14 at 18:32
4

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

It is. It requires at least one of the operands to be an std::string:

int main() 
{
  std::string foo("foo");
  std::string bar("bar");
  std::string foobar = foo + bar;
  std::cout << foobar << std::endl;
}

The problem in your case is that you are trying to add string literals "abc" and "def". These have type const char[4]. There is no operator+ for these types.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

+ will work to concatenate two strings only when at least one operand is of type std::string.

In "abc" + "def", None of the operand is of type std::string.

haccks
  • 104,019
  • 25
  • 176
  • 264