1.作业需求:仿照string类,封装一个My_string类,并实现相关功能
实现过程:
#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *date;
int size;
public:
my_string():size(15)
{
date = new char [size];
date[0]='\0';
cout<<"无参构造完成"<<endl;
}
my_string(const char *str)
{
size=sizeof (str);
date = new char[size];
strcpy(date,str);
cout<<"有参构造完成"<<endl;
}
my_string(int n, char ch)
{
size=n*sizeof(ch);
date = new char[size];
for(int i=0;i<n;i++)
{
date[i]=ch;
}
cout<<"多参构造完成"<<endl;
}
~my_string()
{
delete date;
cout<<"析构函数完成"<<endl;
}
my_string(const my_string &s)
{
this->size=s.size;
this->date=new char[this->size];
strcpy(this->date,s.date);
cout<<"拷贝构造函数"<<endl;
}
my_string & operator=(const my_string &s)
{
this->size=s.size;
this->date=new char[this->size];
strcpy(this->date,s.date);
cout <<"拷贝赋值函数"<<endl;
return *this;
}
const char *c_str()
{
return date;
}
int my_size()
{
return size;
}
bool empty()
{
return strlen(date);
}
char at(int n)
{
if(n<0 ||n >size-1)
{
cout<<"数值越界"<<endl;
return 0;
}
return date[n];
}
void show()
{
cout<<"date = "<<date<<endl;
}
};
int main()
{
string s("hello");
cout<<"s = "<<s<<endl;
my_string s1("hello");
s1.show();
if(s1.empty())
{
cout<<"s1字符串不为空"<<endl;
}else
{
cout<<"s1字符串为空"<<endl;
}
cout<<"s1.at = "<<s1.at(0)<<endl;
s1.show();
my_string s2(5,'A');
s2.show();
s2.show();
cout<<"s2size = "<<s2.my_size()<<endl;
if(s2.empty())
{
cout<<"s2字符串不为空"<<endl;
}else
{
cout<<"s2字符串为空"<<endl;
}
my_string s3;
if(s3.empty())
{
cout<<"s3字符串不为空"<<endl;
}else
{
cout<<"s3字符串为空"<<endl;
}
my_string s4=s1;
s4.show();
my_string s5;
s5=s1;
s5.show();
return 0;
}
实验结果:
![](https://i-blog.csdnimg.cn/blog_migrate/03b77644ae58c6faff7a9091d65b9272.png)