The + operator should not be a member function, but a free function, therefore, transformations can be performed in any of its operands. The easiest way to do this is to write the + = operator as a member, and then use it to implement a free function for the + operator. Sort of:
String operator +( const String & s1, const String & s2 ) { String result( s1 ); return result += s2; }
Like others, you can overload for const char * for efficiency reasons, but the only function above is all you really need.
Please note that your code in its value should give an error for:
String s1("hi"); String s2("hello"); str2 = str1 + "ok";
sort of:
warning: deprecated conversion from string constant to 'char*'
as a string literal (constant), "ok" is const char * , not char * . If your compiler does not give this warning, you should seriously consider updating it.
anon
source share