Can I arbitrarily write an operator+() function for C++’s string class so I don’t have to use <sstream> to concatenate strings?
For example, instead of doing
someVariable << "concatenate" << " this";
Can I add an operator+() so I can do
someVariable = "concatenate" + " this";
?
The
std::stringoperator+does concatenate twostd::strings. Your problem however is that"concatenate"and"this"aren’t twostd::strings; they’re of typeconst char [].If you want to concatenate the two literals
"concatenate"and"this"for whatever reason (usually so you can split strings over multiple lines) you do:And the compiler will realise that you actually want
string someVariable = "concatenate this";If
"concatenate"and"this"were stored instd::strings then the following is valid:OR
Or even
Where
" this"will be automatically converted into anstd::stringobject whenoperator+is invoked. For this conversion to take place at least one of the operands must be of typestd::string.