fork download
  1. #include <algorithm>
  2. #include <cstring>
  3. #include <iostream>
  4.  
  5. class A
  6. {
  7. public:
  8. // construct from string
  9. A () : str(new char[1]()) {}
  10.  
  11. A(const char *s) : str(new char[strlen(s) + 1])
  12. { strcpy(str, s); }
  13.  
  14. // copy construct
  15. A(const A& rhs) : str(new char[strlen(rhs.str) + 1])
  16. { strcpy(str, rhs.str); }
  17.  
  18. // destruct
  19. ~A() { delete [] str; }
  20.  
  21. // assign
  22. A& operator=(const A& rhs)
  23. {
  24. A temp(rhs);
  25. std::swap(str, temp.str);
  26. return *this;
  27. }
  28.  
  29. // implement
  30. void setStr(char * s)
  31. {
  32. A temp(s);
  33. *this = temp;
  34. }
  35.  
  36. const char* getStr() { return str; }
  37.  
  38. private:
  39. char * str;
  40. };
  41.  
  42. using namespace std;
  43.  
  44. int main()
  45. {
  46. A a1;
  47. a1.setStr("abc");
  48. A a2;
  49. a2 = a1;
  50. A a3 = a1;
  51. a2.setStr("456");
  52. cout << a1.getStr() << "\n" << a2.getStr() << "\n" << a3.getStr();
  53. }
  54.  
  55.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
abc
456
abc