image.png

    1. #include <iostream>
    2. #include <string>
    3. #include <cstring>
    4. using namespace std;
    5. class MyString
    6. {
    7. char *p;
    8. public:
    9. MyString(const char *s)
    10. {
    11. if (s)
    12. {
    13. p = new char[strlen(s) + 1];
    14. strcpy(p, s);
    15. }
    16. else
    17. p = NULL;
    18. }
    19. ~MyString()
    20. {
    21. if (p)
    22. delete[] p;
    23. }
    24. MyString(const MyString &s)
    25. {
    26. if (s.p)
    27. {
    28. p = new char[strlen(s.p) + 1];
    29. strcpy(p, s.p);
    30. }
    31. else
    32. p = NULL;
    33. }
    34. MyString &operator=(const MyString s)
    35. {
    36. if (p)
    37. delete[] p;
    38. if (s.p)
    39. {
    40. p = new char[strlen(s.p) + 1];
    41. strcpy(p, s.p);
    42. }
    43. else
    44. p = NULL;
    45. return *this;
    46. }
    47. void Copy(const char *s)
    48. {
    49. if (p)
    50. delete[] p;
    51. if (s)
    52. {
    53. p = new char[strlen(s) + 1];
    54. strcpy(p, s);
    55. }
    56. else
    57. p = NULL;
    58. }
    59. friend ostream &operator<<(ostream &o, const MyString s)
    60. {
    61. o << s.p;
    62. return o;
    63. }
    64. };
    65. int main()
    66. {
    67. char w1[200], w2[200];
    68. while (cin >> w1 >> w2)
    69. {
    70. MyString s1(w1), s2 = s1;
    71. MyString s3(NULL);
    72. s3.Copy(w1);
    73. cout << s1 << "," << s2 << "," << s3 << endl;
    74. s2 = w2;
    75. s3 = s2;
    76. s1 = s3;
    77. cout << s1 << "," << s2 << "," << s3 << endl;
    78. }
    79. }
    • 这个题要搞复制构造函数、重载“=”“<<”运算符,需要用到深拷贝
    • 即使是friend函数也可以在类内实现