Problems with first argument are string when overloading + operator in C ++

I have a 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? 
+4
source share
4 answers

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"; // not 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.

+9
source

No, that will not work. When you define a binary operator as a member of a class, the object should always be on the left.

You can define a function that is not a member of your class.

sort of:

 String operator + ( const char* left, const String& right) { // implementation here } 
+1
source

Global functions are your friend

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

This question has been answered, so only some comments

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

If you do not change the char table that the argument points to (and I don’t think so), this will lead to undefined behavior in the case of string literals) will declare the parameter as const char *, char * allows you to 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 should not be methods that, as you know, form other answers, but if they should have been, they should be const, not return const String.

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

Source: https://habr.com/ru/post/1309106/


All Articles