开发者

Problems with first argument being string when overloading the + operator in C++

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 + "o开发者_如何学Pythonk";//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:

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.


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
}


Global functions are your friend

String operator +( const char* pStr, const String& str )
{
   return String( pStr ) + str;
}


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜