#include <iostream>
#include<cstring>
using namespace std;
class mystring
{
private:
char *str;
int len;
public:
mystring()
{
len=15;
str=new char[len];
*str=0;
cout<<"无参构造"<<endl;
}
mystring(char *p)
{
len=15;
while(len<(int)strlen(p))
{
len=len*2;
}
str=new char[len];
strcpy(str,p);
cout<<"有参构造"<<endl;
}
mystring(const mystring &other)
{
len=other.len;
str=new char[len];
strcpy(str,other.str);
cout<<"拷贝构造"<<endl;
}
mystring& operator=(const mystring &other)
{
strcpy(this->str,other.str);
this->len=other.len;
cout<<"拷贝赋值"<<endl;
return *this;
}
~mystring()
{
delete str;
cout<<"析构函数"<<endl;
}
void show()
{
cout<<"str="<<str<<endl;
}
bool empty()
{
return strlen(str)==0;
}
int size()
{
return strlen(str);
}
char &at(int pos)
{
return *(str+pos);
}
char *c_str()
{
return str;
}
};
int main()
{
mystring s1;
if(s1.empty())
{cout<<"empty"<<endl;}
mystring s2("string is over");
cout<<"s2的size="<<s2.size()<<endl;
mystring s3(s2);
cout<<"s3的下标为5的字符:"<<s3.at(5)<<endl;
s1=s2;
printf("c风格字符串:%s\n",s3.c_str());
s1.show();
s2.show();
s3.show();
return 0;
}