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::string
operator+
does concatenate two std::string
s. Your problem however is that "concatenate"
and "this"
aren't two std::string
s; they're of type const 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:
string someVariable = "concatenate" " this";
And the compiler will realise that you actually want string someVariable = "concatenate this";
If "concatenate"
and "this"
were stored in std::string
s then the following is valid:
string s1 = "concatenate";
string s2 = " this";
string someVariable = s1 + s2;
OR
string s1 = "concatenate";
string someVariable = s1 + " this";
Or even
string someVariable = string("concatenate") + " this";
Where " this"
will be automatically converted into an std::string
object when operator+
is invoked. For this conversion to take place at least one of the operands must be of type std::string
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With