封装string的类
#include <iostream>
#include<cstring>
using namespace std;
class mystring
{
private:
char *str;
int size;
public:
mystring():size(10)
{
str=new char[size];
cout<<"无参构造函数"<<endl;
}
mystring(const char*s)
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
cout<<"有参构造函数"<<endl;
}
mystring(const mystring & other)
{
size=other.size;
str=new char[size+1];
strcpy(str,other.str);
cout<<"拷贝构造函数"<<endl;
}
mystring & operator=(const mystring&other)
{
*(this->str)=*(other.str);
this->size=other.size;
cout<<"拷贝赋值函数"<<endl;
return *this;
}
~mystring()
{
delete str;
cout<<"析构函数"<<endl;
}
bool empty()
{
if(strlen(str)==0){
return true;
}
else{
return false;
}
}
int st_size()
{
cout<<"st_size函数"<<endl;
return size;
}
char *c_str()
{
cout<<"c_str函数"<<endl;
return str;
}
char at(int pos)
{
char *p=str;
for(int i=0;i<pos;i++){
p++;
}
return *p;
}
void show()
{
cout<<"size="<<size<<endl;
cout<<"str="<<str<<endl;
}
};```