仿照string类,封装一个My_string类,并实现相关功能
header.h:
#ifndef HEADER_H
#define HEADER_H
class My_string
{
private:
char *data;
int Capacity;
public:
//无参构造函数,默认长度为15
My_string(); //当前字符串变量的最大容量(capacity())
//有参构造函数
My_string(const char *str); //string s("hello world");
My_string(int n, char ch); //string s1(3,'A');
//拷贝构造函数
My_string(const My_string &other); //string s2 = s;
//拷贝赋值函数
My_string & operator=(const My_string &other); //string s3; s3 = s1;
//获取当前最大容量
int capacity();
//c_str函数
const char *c_str();
//size函数
int size();
//empty函数
bool empty();
//at函数
char at(int i);
//析构函数
~My_string();
};
#endif // HEADER_H
my_string.cpp:
#include <iostream>
#include <cstring>
#include <header.h>
using namespace std;
//无参构造函数,默认长度为15
My_string::My_string() //当前字符串变量的最大容量(capacity())
{
Capacity = 15;
data = new char[Capacity];
data[0] = '\0';
}
//有参构造函数
My_string::My_string(const char *str) //string s("hello world");
{
Capacity = 15;
while((int)strlen(str) > Capacity)
Capacity = strlen(str) * 2;
data = new char[Capacity];
strcpy(data, str);
data[strlen(str)] = '\0';
}
My_string::My_string(int n, char ch) //string s1(3,'A');
{
Capacity = 15;
while(n > Capacity)
Capacity = n * 2;
data = new char[Capacity];
for(int i = 0; i < n; i++)
data[i] = ch;
data[n] = '\0';
}
//拷贝构造函数
My_string::My_string(const My_string &other) //string s2 = s;
{
this->Capacity = other.Capacity;
this->data = new char(other.Capacity);
strcpy(this->data, other.data);
}
//拷贝赋值函数
My_string & My_string::operator=(const My_string &other) //string s3; s3 = s1;
{
delete (this->data);
this->Capacity = other.Capacity;
this->data = new char[Capacity];
strcpy(this->data, other.data);
return *this;
}
//获取当前最大容量
int My_string::capacity()
{
return Capacity;
}
//c_str函数
const char *My_string::c_str()
{
return data;
}
//size函数
int My_string::size()
{
return strlen(data);
}
//empty函数
bool My_string::empty()
{
//cout << strlen(data) << endl;
return strlen(data);
}
//at函数
char My_string::at(int i)
{
return data[i];
}
//析构函数
My_string::~My_string()
{
//cout << "S::析构函数" << endl;
delete data;
}
main.cpp:
#include <iostream>
#include <cstring>
#include <header.h>
using namespace std;
int main()
{
My_string s = "hello";
cout << "s = " << s.c_str() << endl;
My_string s1("hello world");
cout << "s1 = " << s1.c_str() << endl;
My_string s2(31,'A');
cout << "s2 = " << s2.c_str() << endl;
My_string s3 = s;
cout << "s3 = " << s3.c_str() << endl;
My_string s4;
s4 = s1;
cout << "s4 = " << s4.c_str() << endl;
cout << "s4[1] = " << s4.at(1) << endl;
cout << "s4_size = " << s4.size() << endl;
My_string s5;
cout << "s5_size = " << s5.size() << endl;
cout << "s5当前最大容量 = " << s5.capacity() << endl;
cout << "s2当前最大容量 = " << s2.capacity() << endl;
cout << "s2_size = " << s2.size() << endl;
if(s4.empty())
{
cout<<"字符串不为空"<<endl;
}else
{
cout<<"字符串为空"<<endl;
}
return 0;
}
测试结果如下: