1、仿照string类,完成myString 类
#include <iostream>
#include<cstring>
using namespace std;
class myString
{
private:
     char *str;          //记录c风格的字符串
     int size;            //记录字符串的实际长度
public:
   //无参构造
   myString():size(10)
     {
        str = new char[size];         //构造出一个长度为10的字符串
        strcpy(str,"");         //赋值为空串
     }
   //有参构造
    myString(const char *s)          //string  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);
         }
    cout<<"Stu::拷贝赋值函数"<<endl;
    return *this;
      }
    //判空函数
    bool str_empty()
    {
        return !strcmp("",str);
    }
    //size函数
    int str_size()
    {
        return strlen(this->str);
    }
    //c_str函数
    char *s_c_str()
    {
        return  str;
    }
    //at函数
    char &at(int pos)
    {
        return str[pos];
    }
    //加号运算符重载
    const myString operator+(const myString &R)const
        {
            myString c;
            c.str=strcat(this->str,R.str);
            c.size=this->size+R.size;
            return  c;
        }
    //加等于运算符重载
    myString & operator+=(const myString &R)
        {
            this->str=strcat(this->str,R.str);
            this->size+=R.size;
            return  *this;//返回自身的引用
        }
    //关系运算符重载(>)
    bool operator>(const myString &R)const
        {
            return strcmp(this->str,R.str);
        }
    //中括号运算符重载
    char &operator[](int index)
        {
            return str[index];
        }
    //定义遍历
    void show()
        {
            cout<<"字符串:"<<str<<endl;
            cout<<"实际长度:"<<size<<endl;
        }
 };
int main()
{
        myString c1("hello ");
        c1.show();
        myString c2("world");
        c2.show();
        myString c3=c1+c2;
        c3.show();
        if(c1>c2)
        {
            cout<<"yes"<<endl;
        }
        else
        {
            cout<<"no"<<endl;
        }
        c3[0]='*';
        c3.show();
        c3+=c2;
        c3.show();
        cout<<"size="<<c3.str_size()<<endl;
      
        return 0;
}
 

2、思维导图




















