Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an operator+ function for C++'s string class? And to concatenate "literals"?

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";

?

like image 419
trusktr Avatar asked Nov 04 '11 01:11

trusktr


1 Answers

The std::string operator+ does concatenate two std::strings. Your problem however is that "concatenate" and "this" aren't two std::strings; 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::strings 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.

like image 128
AusCBloke Avatar answered Sep 20 '22 10:09

AusCBloke