实现代码
#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)
{
len = other.len;
cstr = new char[len+1]();
strcpy(cstr, other.cstr);
}
~My_string()
{
delete []cstr;
cstr = NULL;
cout<<"析构函数"<<this<<endl;
}
bool empty()
{
return len==0?1:0;
}
int size()
{
return len;
}
char &at(int index)
{
return cstr[index];
}
char* c_str()
{
return cstr;
}
};
int main()
{
My_string s1("hello");
My_string s2 = s1;
My_string s3(s1);
My_string s4;
cout<<"&s1 = "<<&s1<<" &s2 = "<<&s2<<" &s3s = "<<&s3<<" &s4 = "<<&s4<<endl;
cout<<"s1 = "<<s1.c_str()<<endl;
cout<<"s2 = "<<s2.c_str()<<endl;
cout<<"s3 = "<<s3.c_str()<<endl;
cout<<"s3[4] = "<<s3.at(4)<<" s3.size = "<<s3.size()<<" s3.empty = "<<s3.empty()<<endl;
cout<<"s4.empty = "<<s4.empty()<<endl;
char* str = s3.c_str();
cout<<"char* str = "<<str<<endl;
return 0;
}
测试结果
