C++仿照string类,封装一个My_string类,并实现相关功能
代码:
#include <iostream>
#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<<"My_string::无参构造"<<endl;
}
//有参构造
My_string(const char *str)
{
size=sizeof (str);
data = new char[size];
// data[0] = '\0';
strcpy(data,str);
cout<<"My_string::有参构造"<<endl;
}
My_string(int n, char ch)
{
data = new char[n];
size=n;
// data[0] = '\0';
for(int i=0;i<n;i++)
{
data[i]=ch;
}
cout<<"My_string::有参构造1"<<endl;
}
//析构函数
~My_string()
{
delete []data;
data=nullptr;
cout<<"My_string::析构"<<endl;
}
//拷贝构造函数
My_string(const My_string &other):data(new char(other.size)),size(other.size)
{
this->data=other.data;
cout<<"My_string::拷贝构造函数"<<endl;
}
//拷贝赋值函数
My_string & operator=(const My_string &other)
{
this->data = other.data;
this->size = other.size;
cout<<"My_string::拷贝赋值函数"<<endl;
return *this;
}
//c_str函数
char* c_str()
{
return this->data;
}
//size函数
int my_size()
{
return size;
}
//empty函数
bool empty()
{
return size==0?1:0;
}
//at函数
char my_at(int num)
{
return data[num-1];
}
//show
void my_show()
{
cout<<"data= "<<this->data<<endl;
}
};
int main()
{
char str[]="weixinyu";
//有参构造 show函数
My_string str1(str); //有参构造
str1.my_show();
//构造拷贝函数
My_string str2("drp"); //拷贝构造函数
My_string str3(str1);
//c_str函数
cout <<"c_str3= "<<str3.c_str() <<endl;
//size函数
cout <<"str1_size= "<<str1.my_size() <<endl;
//empty函数
if(str1.empty())
{
cout << "str1为空 "<<endl;
}
else
{
cout << "str1为非空 "<<endl;
}
//at函数
cout << "str1第四位 " <<str1.my_at(4) <<endl;
return 0;
}
实现结果: