作业要求:
仿照string类,封装一个My_string类,并实现相关功能
代码如下:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class My_string
{
private:
char *data;
int size;
public:
//无参构造函数,默认值15
My_string():size(15)
{
data = new char[size];
data[0] = '\0';
cout<<"无参构造"<<endl;
}
//有参构造函数
My_string(const char *str):size(strlen(str))
{
data = new char[size];
strcpy(data,str);
cout<<"有参构造"<<endl;
}
//有参构造函数
My_string(int n,char ch):size(n)
{
data = new char[size];
for(int i=0;i<size;i++)
{
data[i] = ch;
}
cout<<"有参构造"<<endl;
}
//析构函数
~My_string()
{
delete []data;
data = nullptr;
size = 0;
cout<<"析构函数"<<endl;
}
//拷贝构造函数
My_string(const My_string &other):size(other.size)
{
data = new char[size];
strcpy(data,other.data);
cout<<"拷贝构造函数"<<endl;
}
//拷贝赋值函数
My_string & operator = (const My_string &other)
{
if(this->size<other.size)
{
delete []data;
data = new char[other.size];
}
this->size = other.size;
strcpy(this->data,other.data);
cout<<"拷贝赋值"<<endl;
return *this;
}
//输出字符串地址函数
char *c_str()
{
return data;
}
//字符串个数输出函数
bool size_t()
{
return size;
}
//empty函数
int empty()
{
return 0 == size;
}
//at函数
char at(int num)
{
if(num<0 || num>size-1)
{
cout<<"所给数据不合理"<<endl;
return -1;
}
return data[num];
}
//遍历
void show()
{
cout<<"data = "<<data<<endl;
cout<<"size = "<<size<<endl;
}
};
int main()
{
My_string s0;
s0.show();
My_string s1("abcdcjsbkcbasjcb");
s1.show();
My_string s5 = "bcde";
s5.show();
s5 = s1;
s5.show();
My_string s2(s1);
s2.show();
My_string s3 = s2;
s3.show();
My_string s4;
s4 = s3;
s4.show();
printf("c_str = %s\n",s4.c_str());
printf("size_t = %d\n",s4.size_t());
cout<<s4.empty()<<endl;
cout<<s4.at(3)<<endl;
return 0;
}
代码执行结果: