+ 5
Why is it that we can use the + operator to concatenate string variables but not string literals?
4 Réponses
+ 8
ShortCode sorry about that, I think the network here is slow or something
+ 5
The usual literals are not std::string literals. They are raw character arrays of a constant size. (called c-strings).
The string class has overloaded operators as members and friends to support concatenation with other strings and c-strings.
But since no overload of + exists for concatenating two c-strings, you get an error when you try to perform "Hello"+" World" or a similar operation.
The workaround for this would be to either wrap one of the c-strings inside a string object and then concatenate it with the other literals, or use the literal operator""s to create std::string literals.
For the first solution:
std::string s3 = "Hello"+std::string(" there!");
And for the second:
std::string s4 = "Hello"+" there!"s;
The second solution uses the operator ""s to initialize a constant c-string as a std::string object, which can be concatenated to other literals. Literals are available since C++11, and are accessible when you use the std::literals namespace. (using namespace std::literals)
+ 4
Are you asking this twice Moses Odhiambo?
+ 4
Moses Odhiambo its okay. I often got that too!