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

#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_
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值