仿照string类,封装一个My_string类,并实现相关功能
//无参构造默认长度为15
//有参构造
//析构函数
//拷贝构造函数
//拷贝赋值函数
//c_str函数
//size函数
//empty函数
//at函数
#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 << "无参构造" << endl;
}
//有参构造1
My_string(const char *str):data(new char[strlen(str)+1]),size(strlen(str))
{
strcpy(data,str);
cout << "有参构造函数" << data << endl;
}
//有参构造2
My_string(int n, char ch):data(new char[n+1]),size(n)
{
for(int i=0;i<n;i++){
data[i] = ch;
}
data[n] = '\0';
cout << "有参构造函数" << data << endl;
}
//析构函数
~My_string(){
delete []data;
cout << "析构函数" << endl;
}
//拷贝构造函数
My_string(const My_string &other):data(new char[other.size+1]),size(other.size){
strcpy(data,other.data);
cout << "拷贝构造函数" << data << endl;
}
//拷贝赋值函数
My_string & operator=(const My_string &other){
delete []data;
data = new char[other.size+1];
strcpy(this->data,other.data);
this->size = other.size;
cout << "拷贝赋值函数" << this->data << endl;
return *this;
}
//c_str函数
char* My_str(){
return this->data;
}
//size函数
int My_size(){
return strlen(this->data);
}
//empty函数
bool My_empty(){
return data[0] == '\0';
}
//at函数
char &M_at(int n){
return this->data[n];
}
};
int main()
{
//有参构造2
My_string s1(20,'A');
//拷贝构造
My_string s2 = s1;
//无参构造+拷贝赋值
My_string s3;
s3 = s1;
//有参构造1
My_string s4("hello world");
//c_str函数
printf("%s\n",s4.My_str());
//size函数
cout << "s1 = " << s1.My_size() << endl;
cout << "s2 = " << s2.My_size() << endl;
cout << "s3 = " << s3.My_size() << endl;
cout << "s4 = " << s4.My_size() << endl;
//at函数
cout << "s4.M_at(3) = " << s4.M_at(3) << endl;
cout << "s4.M_at(6) = " << s4.M_at(6) << endl;
cout << "s4.M_at(9) = " << s4.M_at(9) << endl;
cout << "s4.M_at(0) = " << s4.M_at(0) << endl;
s4.M_at(0) = 'H';
cout << "s4.M_at(0) = " << s4.M_at(0) << endl;
//empty函数
My_string s5;
if(s5.My_empty()){
cout << "空" << endl;
}else{
cout << "不空" << endl;
}
return 0;
}
运行结果:

本文展示了如何在C++中封装一个名为My_string的类,该类模仿了std::string的功能。类包含了无参构造、有参构造(两种情况)、析构、拷贝构造、拷贝赋值函数,以及c_str、size、empty和at等成员函数。在main函数中,对这些功能进行了实例化和使用演示。
280

被折叠的 条评论
为什么被折叠?



