#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造
my_string(){};
//有参构造
my_string(char s,int l)
{
str=new char[l+1];
for(int i=0;i<l;i++)
{
str[i]=s;
}
str[l]=0;
len=l;
}
my_string(char *s)
{
len=strlen(s);
str=new char[len+1];
strcpy(str,s);
str[len]=0;
}
//拷贝构造
my_string(const my_string &o)
{
len=o.len;
str=new char[o.len+1];
for(int i=0;i<o.len+1;i++)
{
*(str+i)=*(o.str+i);
}
//*(o.str+len+1)=0;
}
//拷贝赋值
my_string& operator=(const my_string &r)
{
//防止给自己赋值
if(&r!=this)
{
len=r.len;
if(str!=NULL) //防止内存泄露
{
delete str;
str=NULL;
}
str=new char[r.len+1]; //深拷贝
for(int i=0;i<r.len+1;i++)
{
*(str+i)=*(r.str+i);
}
*(str+len+1)=0;
}
return *this;
}
void show()
{
cout<<"len="<<len<<" str="<<str<<endl;
}
bool my_empty()
{
if(*str==0)
return true;
else
return false;
}
int my_size()
{
return len;
}
//char *my_str()转化为c风格字符串
};
int main()
{
my_string s1('h',4);
my_string s2("string");
my_string s3=s2;
s1.show();
s2.show();
s3.show();
s3=s1;
s3.show();
cout<< s3.my_empty()<<endl;
cout<<s2.my_size()<<endl;
cout<<s1.my_size()<<endl;
cout << "Hello World!" << endl;
return 0;
}
仿照string类,写一个my_string类
最新推荐文章于 2024-10-05 12:07:50 发布