I was playing around with strings in C++ and I don’t understand why the following causes an error when compiled:
string s = "hi";
s += " " + "there!";
Error message:
error: invalid operands of types ‘const char [2]’ and ‘const char [6]’ to binary ‘operator+’
I also tried s+= (" " + "there!"); and it doesn’t work either.
Why can’t I use the binary operator += to concatenate the strings this way?
The problem is you are trying to “add” two literal strings. Literal strings are not of the type std::string in C++, they are like immutable arrays of characters. Adding two together does not make sense, as it would be like adding two pointers together.
You can, however, do this:
This is because there are methods defined in C++ to concatenate C++ strings with C strings.