仿照string类,写一个my_string类
class my_string
{
private:
char *str;
int len;
publuc:
//无参构造
//有参构造
//拷贝构造
//拷贝赋值
//bool my_empty() 判空
//int my_size() 求长度
//char *my_str() 转化为c风格字符串
}
要求:前四个必须实现,后三个尽力而为
#include <iostream>
#include <string.h>
using namespace std;
class my_string
{
private:
char* str;
int len;
public:
//无参构造
my_string()
{
this->str = new char[1]{'\0'};
this->len = 0;
}
//有参构造
my_string(char* str)
{
this->len = strlen(str);
this->str = new char[(this->len)+1];
strcpy(this->str,str);
}
//拷贝构造
my_string(const my_string& O)
{
this->len = O.len;
this->str = new char[O.len]{*(O.str)};
}
//拷贝赋值
my_string& operator=(const my_string& R)
{
if(this!=&R)
{
this->len = R.len;
this->str = new char[R.len]{*(R.str)};
}
return *this;
}
//bool my_empty() 判空
bool my_empty()
{
return this->len==0?true:false;
}
//int my_size() 求长度
int my_size()
{
return this->len;
}
//char *my_str() 转化为c风格字符串
char *my_str()
{
return this->str;
}
};
int main()
{
my_string s0;
cout<<"s0 size="<<s0.my_size()<<endl;
my_string s1("abcdefg");
cout<<"s1 size="<<s1.my_size()<<endl;
my_string s2 = s1;
cout<<"s2 size="<<s2.my_size()<<endl;
my_string s3;
s3 = s1;
cout<<"s3 size="<<s3.my_size()<<endl;
my_string s4 = "123";
cout<<"s4 size="<<s4.my_size()<<endl;
s4 = "45678";
cout<<"s4 size="<<s4.my_size()<<endl;
char* p = s1.my_str();
cout<<p<<endl;
cout << "Hello World!" << endl;
return 0;
}