The chapter 14.1 of "C++ primer 5th edition" reads,
An operator function must either be a member of a class or have at least one parameter of class type.
For example, string("hello")+"world"
compiles "hello"+"world"
doesn't. And when I want to overload the +
on two C strings.
std::string operator+ (const char* s1, const char* s2)
I get the following error.
error: ‘std::string operator+(const char*, const char*)’ must have an argument of class or enumerated type
I have two questions.
Is this restriction part of the language specification? If yes, why C++ designers want to do that?
std::string
has constructor likestring (const char* s);
, which implies that compiler can do implicit class-type conversion fromchar*
tostring
. When we call"hello"+"world"
, why doesn't the compiler convert the twochar*
"s to two strings? After all, there is a overloading "+" on two std::strings.string operator+ (const string& lhs, const string& rhs);
char*
, construct s2 fromchar*
then pass those temporaries to your function. – W.B.