In the first expression
"Hello" + ", world"
the compiler needs to find a suitable function such as operator+(const char *, const char *)
.
No such function exists, so it cannot compile.
Conversely,
hello + ", world"
is looking for one matching operator+(const std::string&, const char*)
, and that overload does exist (it is provided by std::string
).
Note that you even if you could write your own overload:
std::string operator+ (const char *left, const char *right)
{
return std::string(left) + right;
}
(and you can't, as Praetorian points out) it wouldn't be a good idea.
Firstly, with primitive arguments, you'd lose ADL (ie, if the standard library put the operator in namespace std
, it wouldn't normally be visible outside).
Secondly, if you have other libraries with their own string representations (eg. pre-STL stuff like RogueWave, or Qt, etc. etc.) they'd be equally justified in providing an overload for their string type, and the compiler would have no way to choose between them.