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_
阅读全文
0 0
- C++笔试题(剑指offer 面试题2 自己的string类)
- 自己可能用到的笔试面试题(整理C/C++)
- c/c++笔试面试题(2)
- c/c++笔试面试题(2)
- C++笔试题(剑指offer 面试题4 替换字符串中的空格)
- C++笔试题(剑指offer 面试题3 二维数组中查找数)
- C++笔试题(剑指offer 面试题7 两个栈实现队列)
- JAVA --String类笔试面试题
- 【转载】JAVA --String类笔试面试题
- JAVA --String类笔试面试题
- JAVA --String类笔试面试题
- JAVA --String类笔试面试题
- JAVA --String类笔试面试题
- C/C++ 相关笔试题(2)-----微软亚洲技术中心的面试题
- 《剑指offer》面试题3(2)
- C笔试面试题
- 剑指offer面试题--类
- 剑指offer 面试题2
- 那些年我们追的sql注入
- Accept-Encoding: gzip,deflate + libcurl + rt5350
- 中国强军梦
- zhoukao1
- mybatis 一对
- C++笔试题(剑指offer 面试题2 自己的string类)
- MySQL索引总结
- JavaScript的变量作用域和闭包操作
- 前后端分离开发的介绍、原因、相关案例
- MVC模型构建管理系统
- LockSupport
- Dalivik垃圾回收收机制Cocurrent GC简介
- 约束布局解析
- vue-quill-editor自定义图片上传