1.封装mystring类
#include <iostream>
#include <cstring>
using namespace std;
class Mystring
{
private:
char *str; //记录c风格字符串
int sizes; //记录字符串的实际长度
public:
Mystring():sizes(10) //无参构造
{
str = new char[sizes]; //默认设置10字节
strcpy(str, ""); //初始化为空串
}
Mystring(const char *s) //有参构造
{
sizes = strlen(s); //字符串长度
str = new char[sizes+1]; //最后\0算上
strcpy(str, s); //字符串复制
}
~Mystring() //析构函数
{
delete []str; //释放指针指向空间
}
Mystring (const Mystring &other) //拷贝构造函数
{
sizes = other.sizes;
str = new char[sizes+1];
strcpy(str, other.str);
}
Mystring &operator=(const Mystring &other) //拷贝赋值函数
{
delete this;
sizes = other.sizes;
this->str = new char[sizes+1];
strcpy(str, other.str);
return *this;
}
bool empty() //判空函数
{
if (sizes == 0)
return true;
else
return false;
}
int size() //size函数
{
return sizes;
}
const char *c_str() //c_str函数
{
return str;
}
char &at(int pos) //at()函数
{
if(pos >= sizes || pos < 0)
{
cout << "下标不合法" <<endl;
}
return str[pos];
}
const Mystring operator+(const Mystring &R)const //成员函数实现+
{
Mystring temp;
delete temp;
temp.sizes = this->sizes + R.sizes;
temp.str = new char[temp.size];
temp.str = strcat(this->str, R.str);
return temp;
}
Mystring &operator+=(const Mystring &R) //成员函数实现+=
{
strcat(this->str, R.str);
this->sizes = this->sizes + R.sizes;
return *this;
}
bool operator>(const Mystring &R)const //成员函数实现>
{
if(strcmp(this->str, R.str))
{
return true;
}
else
{
return false;
}
}
};
int main()
{
Mystring s1; //无参构造
Mystring s2("hello"); //有参构造
s1 = s2; //拷贝赋值函数
// Mystring s1 = s2; //拷贝构造函数
// Mystring s1;
s1 += s2;
if (s1.empty()) //判空
cout << "空" <<endl;
cout << "s1.size = " << s1.size() <<endl; //size函数
cout << "s1 = " << s1.c_str() <<endl; //c_str函数
cout << "s1[1] = " << s1.at(1) <<endl; //at()函数
if (s1 > s2)
cout << "s1 > s2" <<endl;
return 0;
}
2.思维导图