Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <iostream>
- #include <cstring>
- using namespace std;
- class Str
- {
- char* s;
- int l;
- public:
- Str()
- {
- s=0;
- l=0;
- }
- Str(char* st)
- {
- s = strcopy(st);
- l=strlen(st);
- }
- char* strcopy (const char* st)
- {
- int l=strlen(st);
- char* sc=new char [l+1];
- for (int i=0;i<=l;i++)
- {
- sc[i]=st[i];
- }
- return sc;
- }
- Str (const Str& st)
- {
- s=strcopy((char*)st);
- l=strlen(st);
- }
- ~Str ()
- {
- delete[] s;
- s=0;
- }
- Str& operator=(const Str &st)
- {
- if (s!=0)
- {
- delete[] s;
- s=0;
- }
- s = strcopy(st);
- l=strlen(st);
- return *this;
- }
- Str& operator+=(const Str& rhs) // compound assignment (does not need to be a member,
- { // but often is, to modify the private members)
- /* addition of rhs to *this takes place here */
- int l2=strlen(rhs);
- char* sc=new char [l+l2+1];
- for (int i=0;i<l;i++)
- {
- sc[i]=s[i];
- }
- char* crhs = rhs;
- for (int i=l;i<=l+l2;i++)
- {
- sc[i]=crhs[i-l];
- }
- if (s!=0)
- {
- delete[] s;
- s=0;}
- s=sc;
- l+=l2;
- return *this; // return the result by reference
- }
- // friends defined inside class body are inline and are hidden from non-ADL lookup
- friend Str operator+(Str lhs, // passing first arg by value helps optimize chained a+b+c
- const Str& rhs) // alternatively, both parameters may be const references.
- {
- return lhs += rhs; // reuse compound assignment and return the result by value
- }
- char& operator[](size_t idx) {
- /* actual access, e.g. return mVector[idx]; */
- cerr << "[] non-const" << endl;;
- return s[idx];
- }
- char operator[](size_t idx) const {
- // either actual access, or reuse non-const overload
- // for example, as follows:
- cerr << "[] const" << endl;
- return s[idx];
- }
- operator char*() const
- {
- return s;
- }
- void print()
- {
- cout << s<<endl;
- }
- };
- int main()
- {
- Str s1();
- char * s="qwerty";
- Str s2(s); // принимает char*
- Str s3 (s2); //правильно ли работает конструктор копирование
- s2=s3;
- char * s4=s2;
- s2.print();
- s3.print();
- cout << s4 << endl;
- cout << s3+s2 << endl;
- s3+=s2;
- s3.print();
- s3[3] = 'a';
- s3.print();
- const Str a(s);
- cout << a[5] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement