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_
相关文章推荐
- C++面试题,自己实现String类的构造函数,拷贝构造函数,赋值操作符,append,replace,+运算符重载等
- C++笔试题(剑指offer 面试题3 二维数组中查找数)
- C++笔试题(剑指offer 面试题5 将单向链表数据,逆向打印输出)
- C++笔试题(剑指offer 面试题7 两个栈实现队列)
- C++面试题(二)——自己实现一个String类
- C++面试题(二)——自己实现一个String类
- c/c++笔试面试题(3)
- 关于C++的基础易错知识(源于各种笔试题,自己要记得不断更新)
- C/C++ 相关笔试题(2)-----微软亚洲技术中心的面试题
- C++【常见面试题】String类的实现,以及深拷贝、浅拷贝问题
- C/C++笔试面试题
- 【学习笔记】【C++】自己实现string类
- C/C++常见笔试面试题(二)——软件特性、fseek()函数、逗号运算符、左值和右值
- c/c++笔试面试题_1
- C++面试题:String类的实现
- 剑指offer 面试题13:在O(1)时间删除链表结点(C++版)
- IT公司C++笔试面试题系列(一)
- c/c++笔试面试题(4)
- 排列组合相关笔试面试题(C++)
- 《剑指offer》面试题57 删除链表中重复的结点 C++ 实现 以及 错误总结 (指针问题)!!