仿照string类,实现自定义My_strng类,以及相关操作:
定义私有成员变量,字符串及其长度,定义无参构造函数,有参构造函数,拷贝构造函数,析构函数,定义一些成员函数,判断字符串是否为空,求字符串长度,访问指定位置的字符,转换为c风格的字符串。
#include <iostream>
#include<cstring>
using namespace std;
class my_string
{
private:
char *cstr;
int len;
public:
my_string():cstr(NULL),len(0) {cout<<"无参构造"<<endl;} //无参构造函数
my_string(const char *str) //有参构造函数
{
this->len=strlen(str);
this->cstr=new char[this->len];
strcpy(this->cstr,str);
cout<<"有参构造"<<endl;
}
my_string(const my_string &other) //拷贝构造函数
{
this->len=other.len;
this->cstr=new char[this->len];
strcpy(this->cstr,other.cstr);
cout<<"拷贝构造"<<endl;
}
~my_string() //析构函数
{
if(this->cstr!=NULL)
{
delete this->cstr;
}
cout<<"析构函数"<<endl;
}
bool empty() //判断是否为空
{
if(this->len)
{
cout<<"字符串不为空"<<endl;
return 1;
}
else
{
cout<<"字符串为空"<<endl;
return 0;
}
}
int size() //返回字符串的长度
{
return this->len;
}
char &at(int index) //定位函数
{
for(int j=0;j<this->len;j++)
{
if(j==index-1)
break;
}
return this->cstr[index-1];
}
char *c_str() //转化为c风格字符串
{
return this->cstr;
}
};
int main()
{
my_string s; //s调用无参构造
cout<<"s:";
s.empty(); //s判空
my_string s1("helloya"); //s1调用有参构造
cout<<"s1:";
s1.empty(); //s1判空
cout<<"s1.size="<<s1.size()<<endl; //求s1长度
cout<<"s1.at(5)="<<s1.at(5)<<endl; //访问s1指定位置字符
my_string s2(s1); //s2调用拷贝构造
cout<<"s2.size="<<s2.size()<<endl; //求s2长度
cout<<"s2.at(2)="<<s2.at(2)<<endl; //访问s2指定位置字符
printf("s1=%s\n",s1.c_str()); //s1转化为c风格字符串
return 0;
}
Xmind导图