views:

125

answers:

4

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?
+9  A: 

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:

String operator +( const String & s1, const String & s2 ) {
    String result( s1 );
    return result += s2;
}

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:

String s1("hi");
String s2("hello");
str2 = str1 + "ok";    // not OK!!! 

something like:

warning: deprecated conversion from string constant to 'char*'

as the string literal (constant) "ok" is a const char *, not a char *. If your compiler does not give this warning, you should seriously think about upgrading it.

anon
+2  A: 

No, that's not going to work. When you define a binary operator as a member of a class, the object must always be on the left.

You may be able to define a function that is not a member of your class.

something like:

String operator + ( const char* left, const String& right)
{
    // implementation here
}
Scott Langham
Needs to be const char *
anon
Yes, and needs to be a const char* in the question too.
Scott Langham
@Scott You are quite right - I didn't read the question at all closely. I've updated my answer to reflect this.
anon
+1  A: 

Global functions are your friend

String operator +( const char* pStr, const String& str )
{
   return String( pStr ) + str;
}
Goz
Also needs to be a const char *
anon
Point taken and fixed :)
Goz
+1  A: 

The question was answered so just some remarks

String & operator = (char*);
const String operator+ (char* sA);

If You are not modifying the char table pointed to by the argument (and I don't think so - it would lead to undefined behaviour in case of string literals) declare the parameter as const char*. char* lets You pass a string literal in the current version of the language, but in the next it will be illegal.

const String operator+ (String& s);
const String operator+ (char* sA);

Those shouldn't be methods as You know form other answers, but if they were supposed to be, they should be const, not return const String.

String operator+ (const String& s) const;
String operator+ (const char* sA) const;
Maciej Hehl