Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <cstring>
  4.  
  5. using namespace std;
  6.  
  7. class Str
  8. {
  9. char* s;
  10. int l;
  11. public:
  12. Str()
  13. {
  14. s=0;
  15. l=0;
  16. }
  17. Str(char* st)
  18. {
  19. s = strcopy(st);
  20. l=strlen(st);
  21. }
  22.  
  23. char* strcopy (const char* st)
  24. {
  25. int l=strlen(st);
  26. char* sc=new char [l+1];
  27. for (int i=0;i<=l;i++)
  28. {
  29. sc[i]=st[i];
  30. }
  31. return sc;
  32. }
  33.  
  34. Str (const Str& st)
  35. {
  36. s=strcopy((char*)st);
  37. l=strlen(st);
  38. }
  39. ~Str ()
  40. {
  41. delete[] s;
  42. s=0;
  43. }
  44. Str& operator=(const Str &st)
  45. {
  46. if (s!=0)
  47. {
  48. delete[] s;
  49. s=0;
  50. }
  51. s = strcopy(st);
  52. l=strlen(st);
  53. return *this;
  54. }
  55.  
  56. Str& operator+=(const Str& rhs) // compound assignment (does not need to be a member,
  57. { // but often is, to modify the private members)
  58. /* addition of rhs to *this takes place here */
  59. int l2=strlen(rhs);
  60. char* sc=new char [l+l2+1];
  61. for (int i=0;i<l;i++)
  62. {
  63. sc[i]=s[i];
  64. }
  65. char* crhs = rhs;
  66. for (int i=l;i<=l+l2;i++)
  67. {
  68. sc[i]=crhs[i-l];
  69. }
  70. if (s!=0)
  71. {
  72. delete[] s;
  73. s=0;}
  74. s=sc;
  75. l+=l2;
  76. return *this; // return the result by reference
  77. }
  78.  
  79. // friends defined inside class body are inline and are hidden from non-ADL lookup
  80. friend Str operator+(Str lhs, // passing first arg by value helps optimize chained a+b+c
  81. const Str& rhs) // alternatively, both parameters may be const references.
  82. {
  83. return lhs += rhs; // reuse compound assignment and return the result by value
  84. }
  85.  
  86. char& operator[](size_t idx) {
  87. /* actual access, e.g. return mVector[idx]; */
  88. cerr << "[] non-const" << endl;;
  89. return s[idx];
  90. }
  91. char operator[](size_t idx) const {
  92. // either actual access, or reuse non-const overload
  93. // for example, as follows:
  94. cerr << "[] const" << endl;
  95. return s[idx];
  96. }
  97.  
  98. operator char*() const
  99. {
  100. return s;
  101. }
  102. void print()
  103. {
  104. cout << s<<endl;
  105. }
  106. };
  107. int main()
  108. {
  109.  
  110. Str s1();
  111. char * s="qwerty";
  112. Str s2(s); // принимает char*
  113. Str s3 (s2); //правильно ли работает конструктор копирование
  114. s2=s3;
  115. char * s4=s2;
  116. s2.print();
  117. s3.print();
  118. cout << s4 << endl;
  119. cout << s3+s2 << endl;
  120. s3+=s2;
  121. s3.print();
  122. s3[3] = 'a';
  123. s3.print();
  124. const Str a(s);
  125. cout << a[5] << endl;
  126.  
  127. return 0;
  128. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement