I have an selfmade Stringclass:
//String.h
String & operator = (const String &);
String & operator = (char*);
const String operator+ (String& s);
const String operator+ (char* sA);
.
.
//in main:
String s1("hi");
String s2("hello");
str2 = str1 + "ok";//this is ok to do
str2 = "ok" + str1;//but not this way
//Shouldn't it automatically detect that one argument is a string and in both cases?
The + operator should not be a member function, but a free function, so that conversions can be performed on either of its operands. The easiest way to do this is to write operator += as a member and then use it to implement the free function for operator +. Something like:
As others have suggested, you can overload for const char * for possible efficiency reasons, but the single function above is all you actually need.
Please note that your code as it stands should give an error for:
something like:
as the string literal (constant) “ok” is a
const char *, not achar *. If your compiler does not give this warning, you should seriously think about upgrading it.