“=”重载的概念

1_LI.jpg

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class String
  4. {
  5. private:
  6. char *str;
  7. public:
  8. String(void);
  9. String(const String &);
  10. void PrintString(void);
  11. String& operator=(const char*);
  12. ~String(void);
  13. };
  14. String::String(void):str(new char[1])
  15. {
  16. str[0]='\0';
  17. }
  18. String::String(const String &s)
  19. {
  20. str=new char[strlen(s.str)+1];
  21. strcpy(str,s.str);
  22. }
  23. String& String::operator=(const char *s)
  24. {
  25. delete [] str;
  26. str=new char[strlen(s)+1];
  27. strcpy(str,s);
  28. return *this;
  29. }
  30. void String::PrintString(void)
  31. {
  32. cout<<str<<endl;
  33. }
  34. String::~String(void)
  35. {
  36. delete [] str;
  37. }
  38. int main(void)
  39. {
  40. String s;
  41. s="Hello";
  42. s.PrintString();//Hello
  43. //String s2="Hello"; //Error 是赋值而不是初始化
  44. s="World";
  45. s.PrintString();//World
  46. return 0;
  47. }

深拷贝和浅拷贝

考虑语句”String s1=”Hello”;String s2=”World”;s1=s2;”
14.PNG

  1. String& operator=(const String &s)
  2. {
  3. if(this==&s)
  4. return *this;//防止有人写s=s这种语句而产生不必要的错误
  5. delete [] str;
  6. str=new char[strlen(s.str)+1];
  7. strcpy(str,s.str);
  8. return *this;
  9. }