“=”重载的概念
#include <bits/stdc++.h>
using namespace std;
class String
{
private:
char *str;
public:
String(void);
String(const String &);
void PrintString(void);
String& operator=(const char*);
~String(void);
};
String::String(void):str(new char[1])
{
str[0]='\0';
}
String::String(const String &s)
{
str=new char[strlen(s.str)+1];
strcpy(str,s.str);
}
String& String::operator=(const char *s)
{
delete [] str;
str=new char[strlen(s)+1];
strcpy(str,s);
return *this;
}
void String::PrintString(void)
{
cout<<str<<endl;
}
String::~String(void)
{
delete [] str;
}
int main(void)
{
String s;
s="Hello";
s.PrintString();//Hello
//String s2="Hello"; //Error 是赋值而不是初始化
s="World";
s.PrintString();//World
return 0;
}
深拷贝和浅拷贝
考虑语句”String s1=”Hello”;String s2=”World”;s1=s2;”
String& operator=(const String &s)
{
if(this==&s)
return *this;//防止有人写s=s这种语句而产生不必要的错误
delete [] str;
str=new char[strlen(s.str)+1];
strcpy(str,s.str);
return *this;
}