C++-代入演算子の再ロード
2351 ワード
class String{
private:
char *str;
public:
String():str(NULL){}//
const char * c_str() {return str; }// , , const
char * operator = (const char * s);
~String();
}
// '='->obj = "hello"
char *String :: operator = (const char * s){
if(str)delete[]str;// ,
if(s){
str = new char[strlen(s)+1];// '\0', +1
strcpy(str,s);
}
else
str = NULL;
return str;
}
String::~String(){
if(str) delete []str;
};
int main(){
String s;
s = "Good Luck,"; //-->s.operator = ("")
cout<
MyString S1,S2;
S1 = "this";
S2 = "that";
S1 = S2;
- : S1 “this” "that" , S2 "that" 。 :
* “this”
* S1 S2 , “that” , 。
- : “that” “this” , 。
//
String & operator = (const String & s){
if(str == s.str)return * this;// , 。 :s = s
if(str) delete [] str;
str = new char[strlen(s.str)+1];
strcpy(str,s.str);
return * this;
}
(a=b)=c;// a
:
(a.operator =(b)).operator=(c);
// ,
String::String(String & s)
{
if(s.str){
str = new char[strlen(s.str)+1];
strcpy(str,s.str);
}else{
str = NULL;
}
}