Is it possible to create a + operator for a C ++ string class? And combine the literals?

Can I arbitrarily write an operator+() function for a C ++ string class, so I don’t need to use <sstream> to concatenate strings?

For example, instead of executing

 someVariable << "concatenate" << " this"; 

Is it possible to add operator+() so that I can do

 someVariable = "concatenate" + " this"; 

?

+6
source share
1 answer

std::string operator+ combines two std::string s. However, your problem is that "concatenate" and "this" are not two std::string s; they are of type const char [] .

If you want to combine the two literals "concatenate" and "this" for any reason (usually to split lines across multiple lines):

 string someVariable = "concatenate" " this"; 

And the compiler will understand that you really want a string someVariable = "concatenate this";


If "concatenate" and "this" were stored in std::string , then the following :

 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 to a std::string object when operator+ called. For this conversion, you must have at least one of the operands must be of type std::string .

+15
source

Source: https://habr.com/ru/post/900748/


All Articles