C++笔试题(剑指offer 面试题2 自己的string类)

来源:互联网 发布:美团外卖商家mac版本 编辑:程序博客网 时间:2024/06/11 08:21
#ifndef F_FIND_WORK_CMYSTRING_20171030_JHASKDFJHASF_H_#define F_FIND_WORK_CMYSTRING_20171030_JHASKDFJHASF_H_#include <stdio.h>/*剑指offer 面试题2自己的string类1.复制构造函数 不能 传值,只能传引用2.比较好的 赋值构造函数 和 拷贝构造函数*/class CMyString{public:    CMyString(char *pValue = NULL)    {        if(pValue)        {            m_pValue = new char[strlen(pValue) + 1];            strcpy(m_pValue, pValue);        }    }    CMyString(const CMyString &Other)    {        if(!m_pValue)        {            delete m_pValue;            m_pValue = NULL;        }        m_pValue = new char[strlen(Other.m_pValue) + 1];        strcpy(m_pValue, Other.m_pValue);    }    //  CMyString(CMyString Other)//异常, 复制构造函数 不能 传值,只能传引用    //  {    //      m_nValue = Other.m_nValue;    //  }    CMyString& operator =(const CMyString & Other)    {        if(this != &Other)        {            CMyString aTemp(Other);            char *pTemp = aTemp.m_pValue;            aTemp.m_pValue = m_pValue;            m_pValue = pTemp;        }//此处会自动调用 aTemp的析构函数,将m_pValue之前的内存释放掉        return *this;    }    ~CMyString()    {        if(!m_pValue)        {            delete m_pValue;            m_pValue = NULL;        }    }    void Printf()    {        TRACE("\n\n m_nValue: %s\n\n", m_pValue);    }private:    char *m_pValue;};//测试void F_Test2_CMyString(){    //复制构造函数 不能 传值,只能传引用    CMyString a("aDSFHDH");    CMyString b = a;//产生新对象,和b(a)等价, 调用拷贝构造函数(CMyString(const CMyString &Other))    b.Printf();    CMyString c(a); //产生新对象,调用拷贝构造函数(CMyString(const CMyString &Other))    c.Printf();    CMyString d;    d = a;          //没产生新对象, 调用复制构造函数(重载=:  CMyString& operator =(const CMyString & Other))    }#endif//F_FIND_WORK_CMYSTRING_20171030_JHASKDFJHASF_H_
原创粉丝点击