仿照string类,写一个my_string类
代码
#include<iostream>
#include<string.h>
using namespace std;
class my_string
{
private:
char* str;
int len;
public:
~my_string()
{
if(str!=NULL)
delete str;
}
my_string()
{
this->str=NULL;
this->len=0;
}
my_string(char* s)
{
this->str=s;
this->len=strlen(s);
}
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(my_string &m):str(m.str),len(m.len){}
my_string &operator=(const my_string &R)
{
if(this!=&R)
{
this->str=R.str;
this->len=R.len;
}
return *this;
}
bool my_empty()
{
if(len==0)
return true;
else
return false;
}
int my_size()
{
return len;
}
char *my_str()
{
return (char *)str;
}
void display()
{
cout<<"str:"<<str<<endl;
cout<<"len:"<<len<<endl;
}
};
int main()
{
cout<<"有参构造"<<endl;
my_string s1("hello");
s1.display();
cout<<endl<<"重载函数"<<endl;
my_string s4('h',5);
s4.display();
cout<<endl<<"拷贝构造"<<endl;
my_string s2(s1);
s2.display();
cout<<endl<<"拷贝赋值"<<endl;
my_string s3("good");
s3.display();
s3=s2;
s3.display();
cout<<endl<<"判空"<<endl;
my_string s5;
cout<<(s1.my_empty()?"yes":"no")<<endl;
cout<<(s5.my_empty()?"yes":"no")<<endl;
cout<<endl<<"求长度"<<endl;
cout<<"s1:"<<s1.my_size()<<endl;
cout<<"s5:"<<s5.my_size()<<endl;
cout<<endl<<"转化为c风格字符串"<<endl;
cout<<"s1:"<<s1.my_str()<<endl;
}
结果
