Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <String>
  3. using namespace std;
  4.  
  5. class String
  6. {
  7. struct string_info
  8. {
  9. char* str;
  10. int length;
  11. } *str_ptr;
  12.  
  13. public:
  14. String(const char *);
  15. String();
  16. String(const String &);
  17. String& operator=(const char *);
  18. String& operator=(const String &);
  19. ~String();
  20.  
  21. friend ostream& operator<<(ostream&, String&);
  22. friend istream& operator>>(istream&, String&);
  23.  
  24. friend int operator==(String& x, char* str)
  25. {
  26. return strcmp(x.str_ptr->str, str) == 0;
  27. }
  28.  
  29. friend int operator==(String& x, String& y)
  30. {
  31. return strcmp(x.str_ptr->str, y.str_ptr->str) == 0;
  32. }
  33. };
  34.  
  35. String::String()
  36. {
  37. str_ptr = new string_info;
  38. str_ptr->str = 0;
  39. str_ptr->length = 1;
  40. }
  41.  
  42. String::String(const char* str)
  43. {
  44. str_ptr = new string_info;
  45. str_ptr->str = new char[strlen(str) + 1];
  46. strcpy(str_ptr->str, str);
  47. str_ptr->length = 1;
  48. }
  49.  
  50. String::String(const String& x)
  51. {
  52. x.str_ptr->length++;
  53. str_ptr = x.str_ptr;
  54. }
  55.  
  56. String::~String()
  57. {
  58. if (--str_ptr->length == 0) {
  59. delete str_ptr->str;
  60. delete str_ptr;
  61. }
  62. }
  63.  
  64. String& String::operator=(const char* str)
  65. {
  66. if (str_ptr->length > 1) { // разъединить себя
  67. str_ptr->length--;
  68. str_ptr = new string_info;
  69. }
  70. else if (str_ptr->length == 1)
  71. delete str_ptr->str;
  72.  
  73. str_ptr->str = new char[strlen(str) + 1];
  74. strcpy(str_ptr->str, str);
  75. str_ptr->length = 1;
  76. return *this;
  77. }
  78.  
  79. String& String::operator=(const String& x)
  80. {
  81. x.str_ptr->length++;
  82. if (--str_ptr->length == 0) {
  83. delete str_ptr->str;
  84. delete str_ptr;
  85. }
  86. str_ptr = x.str_ptr;
  87. return *this;
  88. }
  89.  
  90. ostream& operator<<(ostream& str, String& x)
  91. {
  92. return str << x.str_ptr->str << "\length";
  93. }
  94.  
  95. istream& operator>>(istream& str, String& x)
  96. {
  97. char buf[256];
  98. str >> buf;
  99. x = buf;
  100. cout << x << "\length";
  101. return str;
  102. }
  103.  
  104. int main()
  105. {
  106.  
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement