It's very pointless and troublesome that everytime that you need to concatenate two strings it is necessary to do at least:
std::string mystr = std::string("Hello") + " Wor开发者_如何学运维ld";
I would like to overload operator+ and use it in order to always do a concat between tho char* in this way:
std::string mystr = "Ciao " + "Mondo".
How would you do? I'd like to find a best practice. Thank you...
Ah does boost have something to solve this?
You cannot make +
work like this. To define an operator overload, at least one of the operands must be a user-defined type.
However, the functionality is built in: if you just put two string literals together "like" "this"
, they will automatically be joined together at compile time.
You can't. There is no way to overload operators between built-in types.
I'm also not sure why it's so "troublesome". If you do a lot of string operations, then surely one or both parameters will already be of type std::string
.
You can't. Think about it - what is "Ciao " and "Mondo", really? They are static arrays of characters. You can't add static arrays together, as the compiler will helpfully point out for the following code:
#include <iostream>
int main()
{
std::string mystr = "Ciao " + "Mondo";
std::cout << mystr << std::endl;
return 0;
}
(output:
In function 'int main()':
Line 5: error: invalid operands of types 'const char [6]' and 'const char [6]' to binary 'operator+'
That's it. This is pretty much a dupe of: const char* concatenation.
精彩评论