Chr*_*_45 4 c++ operator-overloading
我有一个自制的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?
Run Code Online (Sandbox Code Playgroud)
小智 9
+运算符不应该是成员函数,而应该是自由函数,以便可以对其任一操作数执行转换.最简单的方法是将operator + =作为成员编写,然后使用它来实现operator +的自由函数.就像是:
String operator +( const String & s1, const String & s2 ) {
String result( s1 );
return result += s2;
}
Run Code Online (Sandbox Code Playgroud)
正如其他人所建议的那样,出于可能的效率原因,你可以为const char*重载,但上面的单个函数就是你真正需要的.
请注意,您的代码应该给出错误:
String s1("hi");
String s2("hello");
str2 = str1 + "ok"; // not OK!!!
Run Code Online (Sandbox Code Playgroud)
就像是:
warning: deprecated conversion from string constant to 'char*'
Run Code Online (Sandbox Code Playgroud)
作为字符串文字(常量)"ok"是a const char *,而不是a char *.如果您的编译器没有提供此警告,您应该认真考虑升级它.