1. 源代码
#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char *str; //指向字符串
int size; //记录字符串的长度
public:
//无参构造
myString():size(10)
{
str = new char[size]; //构造一个长度为10的字符串
strcpy(str,"");
}
//有参构造
myString(const char * s) //myString s("hello world")
{
size = strlen(s);
str =new char[size +1];
strcpy(str,s);
}
//拷贝构造
myString(const myString &other):str(new char(*other.str)),size(other.size)
{
cout<<"拷贝构造"<<endl;
}
//析构函数
~myString()
{
delete str;
cout<<"析构函数"<<endl;
}
//拷贝赋值函数
myString &operator=(const myString &other)
{
if(this != &other)
{
this->size=other.size;
//判断原来指针空间是否被清空
if(this->str != NULL)
{
delete this->str;
}
this->str = new char(*other.str);
}
return *this;
}
//判空函数
bool empty()
{
if(this->size !=0)
{
return false;
}
return true;
}
//size 函数
int myString_size()
{
return this->size;
}
//c_str 函数
char *c_str()
{
return this->str;
}
//at 函数
char &at(int pos)
{
return *(this->str+pos-1);
}
//加号运算符重载
const myString operator+(const myString &R)const
{
myString c;
c.size=this->size+R.size;
strcat(c.str,this->str);
strcat(c.str,R.str);
return c;
}
//加等于运算符重载
myString & operator+=(const myString &R)
{
this->size=this->size+R.size;
strcat(this->str,R.str);
return *this;
}
//关系运算符重载
bool operator>(const myString &R)const
{
if(stricmp(this->str,R.str) < 0)
{
return false;
}
return true;
}
//中括号运算符重载
char & operator[](int index)
{
return *(this->str+index-1);
}
//展示函数
void show()
{
cout<<this->str<<endl;
}
};
int main()
{
//有参构造
myString s("hello world");
s.show();
s.empty();
myString z;
z=s;
z.show();
myString x("Bei jing");
s+=x;
s.show();
if(s>z)
{
cout<<"s>z"<<endl;
}
else
{
cout<<"s<z"<<endl;
}
s.~myString();
x.~myString();
z.~myString();
return 0;
}
2. 思维导图