string initialazation compile error

If i code the following, it compiles and works well:

1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
#include <iostream>
using namespace std;

int main() {
string s0 ("middle");
string s1 = "beginning " + s0 + " end";

cout << s1 << endl;

return 0;
}



Now if i code the following, i got a complie error line 7:
invalid operands of types 'const char [11]' and 'const char [5]' to binary 'operator+'



1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
#include <iostream>
using namespace std;

int main() {
string s0 ("middle");
string s1 = "beginning " + " end";

cout << s1 << endl;

return 0;
}



I am missing something but didn't found what ... help !
string s1 = "beginning " + s0 + " end";

This equates to:
std::string s1( operator+("beginning", operator+(s0, "end")) ) ;

There is always a std::string involved with the operator+ chaining.


string s1 = "beginning " + " end";
is equivalent to:

std::string s1(operator+("beginning " + " end")) ;

And you'll notice there is no std::string involved in that operator+. Your compiler is telling you that you can't add char arrays together. You may add one to a std::string, but you can't add it to another char array.

[edit: Fixed missing paren.]
Last edited on
muchos gracias ! I can see that I've still a lot to learn !!!

Don't know common forum practices but one can mark this solved ... please tell me if I've to do something for that ?
At the top of this page there is a button that says "Mark as solved".
Topic archived. No new replies allowed.