1

Possible Duplicate:
Concatenate two string literals

Why doesn't this work ?

const std::string exclam = "!";          
const std::string message = "Hello" + ", world" + exclam;

BUT this works fine

const std::string exclam = "!";       
const std::string message = exclam +
"Hello" + ", world" ;     

Please explain to me.

Thanks

Community
  • 1
  • 1
samantha
  • 565
  • 3
  • 13
  • 29

5 Answers5

5

The reason is that there is no operator+ for adding two string literals, and it is not needed. Your first example works if you just remove the +.

const std::string message = "Hello"  ", world" + exclam;

because preprocessor compiler magic*) will add the two adjacent literals together.

The second example works because std::string does have an operator+ that adds a string literal. The result is another string, that can concatenate the next literal.


*) Translation phase 6 - Adjacent string literal tokens are concatenated.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
3

Because expression "Hello" + ", world" doesn't involve any std::string, but two const char[] arguments. And there is no operator+ with that signature. You have to convert one of those to std::string first:

const std::string message = std::string("Hello") + ", world" + exclam;
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 1
    This would work, too: `const std::string message = "Hello" + (", world" + exclam);` – jrok Jun 12 '12 at 21:52
1

std::string has a + operator which is what is being used in the second example. const char * does not have that operator, which is being used in the first example.

Anon Mail
  • 4,660
  • 1
  • 18
  • 21
0

It's down to associativity.

The second case begins (from the left) evaluation with std::string which is concatenated with operator+. The first case begins with const char * and no concatenation operator+ exists for that.

John
  • 6,433
  • 7
  • 47
  • 82
0

The "const string doesn't work if appended at the end" is a red herring. This doesn't work, either:

const std::string message = "Hello" + ", world";

The reason this doesn't work has been explained in the other answers.

David Hammen
  • 32,454
  • 9
  • 60
  • 108