1、模仿写一个My_string,功能和string差不多
#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char* cstr;
int len;
public:
My_string():cstr(NULL),len(0)//无参构造
{
}
My_string(const char* str)//有参构造
{
len = strlen(str);
cstr = new char[len+1]();
strcpy(cstr,str);
}
My_string(const My_string &other)//拷贝构造
{
// this->cstr = new char(*(other.cstr));//深拷贝
this->len = other.len;
cstr = new char[len+1]();
strcpy(cstr,other.cstr);
}
~My_string()//析构
{
delete cstr;//释放指针成员的空间
}
bool empty(){return (strlen(cstr) == 0 && len == 0);}//判空
int size(){return len;}//返回长度
char &at(int index){return cstr[index];}//定位
char* c_str(){return cstr;}//传化为C风格字符串
};
int main()
{
My_string s1;
cout<<s1.empty()<<endl;
My_string s2("my hello");
cout<<s2.empty()<<endl;
cout<<s2.size()<<endl;
cout<<s2.at(4)<<endl;
char* str = s2.c_str();
cout<<str<<endl;
return 0;
}