//无参构造默认长度为15
My_string():size(15) { data = new char[size]; data[0] = '\0'; }
//有参构造
My_string(const char *str){}
//有参构造
My_string(int n, char ch){}
//析构函数
~My_string(){}
//拷贝构造函数
//拷贝赋值函数
//c_str函数
//size函数
//empty函数
//at函数
代码
#include <iostream>
#include<string.h>
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=sizeof (str);
data = new char[size];
strcpy(data,str);
cout<<"有参构造"<<endl;
}
My_string(int n, char ch)
{
data = new char[n];
size=n;
for(int i=0;i<n;i++)
{
data[i]=ch;
}
cout<<"有参构造1"<<endl;
}
//析构函数
~My_string()
{
delete []data;
data=nullptr;
cout<<"析构函数"<<endl;
}
//拷贝构造函数
My_string(const My_string &other):data(new char[other.size]),size(other.size)
{
strcpy(data,other.data);
cout<<"拷贝构造函数"<<endl;
}
//拷贝赋值函数
My_string &operator=(const My_string &other)
{
if(other.size >size)
{
delete []data;
data = new char[other.size];
}
strcpy(data,other.data);
size = other.size;
cout<<"拷贝赋值函数"<<endl;
return *this;
}
//c_str函数
const char *c_str()
{
return data;
}
//size函数
int s_size()
{
return strlen(this->data);
}
//empty函数
bool empty()
{
return data[0] == 0;
}
//at函数
char &at(int n)
{
return data[n];
}
};
int main()
{
My_string s1("hello");
cout<<endl;
My_string s2(10,'A');
cout<<endl;
My_string s3 = s2;
My_string s4;
s4 = s1;
cout<<endl;
printf("%s\n",s1.c_str());
printf("%s\n",s2.c_str());
cout<<endl;
printf("s1 size = %d\n",s1.s_size());
printf("s2 size = %d\n",s2.s_size());
cout<<endl;
My_string s5;
if(s5.empty())
{
cout<<"空"<<endl;
}
else
{
cout<<"不空"<<endl;
}
s1.at(2) = 'L';
cout<<s1.at(2)<<endl;
cout<<s1.at(1)<<endl;
cout<<endl;
return 0;
}
执行实现结果