Advertisement
szaszm01

c++ string class example

Apr 25th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. class String {
  5.     char *p;
  6.     unsigned int length;
  7.  
  8. public:
  9.     // 1
  10.     String()
  11.         :p(new char[0]), length(0)
  12.     {
  13.         std::cout << "1, p="<< (void*)p << ", length=" << length << std::endl;
  14.     }
  15.  
  16.     // 2
  17.     String(char *p) :p(p), length(strlen(p)) { std::cout << "2" << std::endl; }
  18.  
  19.     // 3
  20.     String(const String &s) {
  21.         if(!s.p) throw "3 err";
  22.         length = strlen(s.p);
  23.         p = new char[length+1];
  24.         strncpy(p, s.p, length + 1);
  25.         std::cout << "3" << std::endl;
  26.     }
  27.  
  28.     // 4
  29.     ~String() {
  30.         std::cout << "4" << std::endl;
  31.     }
  32.  
  33.     // 5
  34.     String operator+(String &s) {
  35.         char *resp;
  36.         if(!p || !s.p) {
  37.             throw "5 err";
  38.         }
  39.  
  40.         resp = new char[length + s.length + 1];
  41.         strncpy(resp, p, length + 1);
  42.         strncpy(resp + length, s.p, s.length + 1);
  43.         std::cout << "5" << std::endl;
  44.         return resp;
  45.     }
  46.  
  47.     // 6
  48.     char &operator[](int i) {
  49.         std::cout << "6" << std::endl;
  50.         return p[i];
  51.     }
  52.  
  53.     // 7
  54.     String &operator=(String &s) {
  55.         if(&s == this) return *this;
  56.         std::cout << "7" << std::endl;
  57.         if(p) delete[] p;
  58.         length = s.length;
  59.         p = new char[length + 1];
  60.         strncpy(p, s.p, length + 1);
  61.         return *this;
  62.     }
  63.  
  64.     String &operator=(const String &s) {
  65.         if(&s == this) return *this;
  66.         std::cout << "7rval" << std::endl;
  67.         if(p) delete[] p;
  68.         length = s.length;
  69.         p = new char[length + 1];
  70.         strncpy(p, s.p, length + 1);
  71.         return *this;
  72.     }
  73. };
  74.  
  75. int main() {
  76.     using namespace std;
  77.  
  78.     cout << "eleje" << endl;
  79.     String s1("rejtvény");
  80.     cout << "s1 létrehozás után" << endl;
  81.     String s2;
  82.     cout << "s2 után" << endl;
  83.     String s3 = s2;
  84.     cout << "s3 után" << endl;
  85.  
  86.     char c = s3[3];
  87.     cout << "operator[] után" << endl;
  88.     s2 = s3;
  89.     cout << "operator= után" << endl;
  90.     s2 = s3 + s2 + s1;
  91.     cout << "operator+, operator= után" << endl;
  92.    
  93.     return 0;
  94. }
  95.  
  96. namespace {
  97. struct C {
  98.     ~C() { std::cout << "main után" << std::endl; }
  99. } _c;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement