您的位置:首页 > 编程语言 > C语言/C++

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

2017-11-06 19:32 363 查看
#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_
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: