首页 > 编程语言 > 详细

C++ 实现简单的string

时间:2021-03-17 17:18:31      阅读:18      评论:0      收藏:0      [点我收藏+]
/*
实现一个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;
};

 

C++ 实现简单的string

原文:https://www.cnblogs.com/LuckCoder/p/14549998.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!