C++ 实现简单的string

/*
实现一个string满足基本用法
*/

class MyString
{
public:
    //默认参数
    MyString(const char *str=""):m_str(strcpy(new char[strlen(str)+1], str))
    {

    }

    ~MyString(void)
    {
        if (m_str)
        {//数组形式的删除内存
            delete []m_str;
            m_str = nullptr;
        }
    }

    //深拷贝构造
    MyString(const MyString&that):m_str(strcpy(new char[strlen(that.m_str) + 1], that.m_str))
    {

    }
    
    //深拷贝赋值
    MyString&operator=(const MyString&that)
    {
        //防止紫赋值
        if (&that!=this)
        {
            MyString temp(that);//深拷贝构造,temp是i2的临时对象
            swap(m_str, temp.m_str);
        }

        return  *this;
    }

    
    const char *c_str(void)const
    {
        return m_str;
    }

private:
    char* m_str;
};

 

posted @ 2021-03-17 16:12  Truman001  阅读(93)  评论(0编辑  收藏  举报