simple question on "const" and "string"

I was confused with below code snippet. What is problem with this code?

const string a = "!";
const string b = "hello" + "world" + a ;

It says "+ can't add 2 pointers".
But, if the code is changed as below, it works:

const string a = "hello";
const string b = a + "world" + "!" ;


Thanks for your illustration.
Okay, I figured it out. For 2nd case, string concatenation occurs 2 times; but in 1st case when first 2 string literal is added it causes the problem, as '+' has left associativity.
That's because there is no operator+ for two string literals.

string + string = string
string + literal = string
literal + string = string
literal + literal = error

So you would have to make a string out of at least one literal:

const string b = string("hello") + "world" + a ;
the literal "something" is a character array ( C string ) std::string a is a class wrapper for that ( C++ string )
The C++ string library overloads the + operator to work with strings, here is a list of overloads: http://www.cplusplus.com/reference/string/operator+/

To make + work for C strings you'll need to convert one of them to a C++ string
eg:
string b = string("hello") + "world" + a ;

BTW why are your strings const?
Just wondering, why would you ever try to add two string literals. Is there any case when you'd want "Hello" + "World" as opposed to "HelloWorld".
Even if you needed to do that, you can do it without the + operator:

 
cout << "Hello "    "World";
Just wondering, why would you ever try to add two string literals. Is there any case when you'd want "Hello" + "World" as opposed to "HelloWorld".

Not exactly in this form, however consider this:

1
2
3
static const char* weekdayNames[]={"Monday","Tuesday","Wednesday",...};
[...]
weekdayNames[wday]+", "+...;


One could use string instead of const char*, but that can bring considerable code size overhead, especially for arrays larger than that.
Topic archived. No new replies allowed.