仿照string类,实现自定义My_string类,以及相关操作
#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char *cstr;
int len;
public:
My_string() //无参构造
{
this->cstr = NULL;
len = 0;
cout << "My_string::无参构造" << endl;
}
My_string(const char *str) //有参构造
{
len = strlen(str);
this->cstr = new char[len+1];
strcpy(cstr,str);
*(cstr+len) = '\0';
cout << "My_string::有参构造" << endl;
}
My_string(const My_string &other) //拷贝构造
{
len = other.len;
this->cstr = new char[other.len+1];
strcpy(cstr, other.cstr);
*(cstr+len) = '\0';
cout << "My_string::拷贝构造" << endl;
}
~My_string() //析构函数
{
if(NULL != cstr)
{
delete []cstr;
}
cout << "My_string::析构函数" << endl;
}
bool empty() //判断是否为空
{
if(len)
{
return true;
}else
{
return false;
}
}
int size() //返回字符串的长度
{
return len;
}
char &at(int index) //定位函数
{
if(len >= index)
{
return *(cstr+index);
}else
{
static char error = -1;
cout<< "**********data error**********" <<endl;
return error;
}
}
const char *c_str() //转化为C风格字符串
{
const char *p = cstr;
return p;
}
};
int main()
{
//S1无参构造
My_string s1;
if(s1.empty())
{
cout<< "s1不为空" <<endl;
}else
{
cout<< "s1为空" <<endl;
}
cout << "******************************" << endl;
//S2有参构造
My_string s2("ni hao shijie");
for(int i=0; i<s2.size(); i++)
{
cout<<s2.at(i);
}
cout<<endl;
cout << "******************************" << endl;
//at超出范围报错
cout<< "使用at超出范围报错>>>" <<endl;
s2.at(100);
cout << "******************************" << endl;
//转换为C语言风格字符串
char str1[s2.size()+1];
const char *p1 = s2.c_str();
strcpy(str1, p1);
str1[s2.size()] = '\0';
cout<< "str1 = " << str1 <<endl;
cout << "******************************" << endl;
//S3拷贝构造
My_string s3(s2);
for(int i=0; i<s3.size(); i++)
{
cout<<s3.at(i);
}
cout<<endl;
return 0;
}