#include<iostream>
#include<cstring>
using namespace std;
class String
{
public:
String (const char *p=nullptr)
{
if(p!=nullptr)
{
_pstr=new char[strlen(p)+1];
strcpy(_pstr,p);
cout<<"string(const char *p=nullptr)"<<endl;
}
else
{
_pstr=new char[1];
*_pstr='\0';
}
}
~String()
{
delete[]_pstr;
_pstr=nullptr;
}
String (const String &str)
{
_pstr=new char[strlen(str._pstr)+1];
strcpy(_pstr,str._pstr);
}
String &operator =(const String &src)
{
if(this==&src)
{
return *this;
}
delete[]_pstr;
_pstr=new char[strlen(src._pstr)+1];
strcpy(_pstr,src._pstr);
cout<<"调用了="<<endl;
}
bool operator>(const String &src)
{
return strcmp(_pstr,src._pstr)>0;
}
bool operator<(const String &src)
{
return strcmp(_pstr,src._pstr)<0;
}
bool operator==(const String &src)
{
return strcmp(_pstr,src._pstr)<0;
}
int length() const{
return strlen(_pstr);
}
char& operator[](int index)
{
return _pstr[index];
}
const char & operator[](int index) const {
return _pstr[index];
}
class iterator{
public:
iterator(char *p=nullptr):_p(p){}
bool operator!=(const iterator &it)
{
return _p!=it._p;
}
void operator++()
{
++_p;
}
char& operator*()
{
return *_p;
}
private:
char *_p;
};
iterator begin()
{
return iterator(_pstr);
}
iterator end()
{
return iterator(_pstr+length());
}
private:
char *_pstr;
friend String operator+(const String &lhs,const String &rhs);
friend ostream& operator<<(ostream &out,const String &str);
};
String operator+(const String &lhs,const String &rhs)
{
String tmp;
tmp._pstr=new char[strlen(lhs._pstr)+strlen(rhs._pstr)+1];
strcpy(tmp._pstr,lhs._pstr);
strcat(tmp._pstr,rhs._pstr);
return tmp;
}
int main(void)
{
String s1="abcdefg";
s1="abcdfs";
String::iterator it=s1.begin();
for(;it!=s1.end();++it)
{
cout<<*it<<" ";
}
cout<<endl;
for(char ch:s1)
{
cout<<ch<<" ";
}
cout<<endl;
return 0;
}