Created
April 11, 2019 14:23
-
-
Save v14dislav/cbfb3615f41791ac8d4fc0f5b7ac750e to your computer and use it in GitHub Desktop.
Operator overloading []
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <string.h> | |
| using namespace std; | |
| class SubString; | |
| class String{ | |
| public: | |
| char *str; | |
| size_t size; //len +1 | |
| String(const char *s); | |
| void append(const String &other); | |
| String(bool dummy,const char *s); | |
| String(size_t n, char c); | |
| String(String const & obj); | |
| String& operator=(const String & obj); | |
| SubString operator[](int i) const; | |
| ~String(); | |
| }; | |
| class SubString{ | |
| public: | |
| char *str; | |
| int offset; | |
| size_t size; //len +1 | |
| SubString(int i,const char *s); | |
| SubString(size_t n, char c); | |
| SubString(SubString const & obj); | |
| SubString& operator=(const SubString & obj); | |
| String operator[](int i) const; | |
| ~SubString(); | |
| }; | |
| String::String(bool dummy, const char *s=""){ | |
| size=strlen(s); | |
| str=new char[size+1]; | |
| for(int i=0;i<(signed)size+1;++i){ | |
| *(str+i)=*(s+i); | |
| } | |
| } | |
| SubString String:: operator[](int i) const{ | |
| char stroka[this->size-i+1]; | |
| for(int k=0;k<((signed)this->size-i+1);++k){ | |
| stroka[k]=*(this->str+i+k); | |
| } | |
| return SubString(i,stroka); | |
| } | |
| SubString:: SubString(int i, const char *s=""){ | |
| offset=i; | |
| size=strlen(s); | |
| str=new char[size+1]; | |
| for(int i=0;i<(signed)size+1;++i){ | |
| *(str+i)=*(s+i); | |
| } | |
| } | |
| SubString:: SubString(size_t n, char c){ | |
| size=n; | |
| str=new char[size+1]; | |
| for(int i=0;i<(signed)size;++i){ | |
| *(str+i)=c; | |
| } | |
| *(str+size)='\0'; | |
| } | |
| SubString::SubString(SubString const & obj){ | |
| this-> size=obj.size; | |
| char *stroka=new char[size+1]; | |
| this->str=stroka; | |
| strcpy(str,obj.str); | |
| } | |
| SubString& SubString:: operator=(const SubString & obj){ | |
| delete [] str; | |
| this-> size=obj.size; | |
| str=new char[size+1]; | |
| strcpy(str,obj.str); | |
| return *this; | |
| } | |
| String SubString:: operator[](int i) const{ | |
| if(i-offset==1) return String(0,""); | |
| char stroka[i-offset+1]; | |
| for(int k=0;k<i-offset;++k){ | |
| stroka[k]=*(this->str+k); | |
| } | |
| stroka[i-offset]='\0'; | |
| return String(0,stroka); | |
| } | |
| SubString::~SubString(){ | |
| delete [] str; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment