#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_
C++笔试题(剑指offer 面试题2 自己的string类)
最新推荐文章于 2022-07-13 09:53:19 发布