C++面试题模拟实现String
来源:互联网 发布:网络科学导论 课程 编辑:程序博客网 时间:2024/05/29 15:33
C++ 的一个常见面试题是让你实现一个 String 类,通常面试官只会给十五分钟左右,不可能要求具备 std::string 的功能,但至少要求能正确管理资源不存在内存泄漏。具体来说:
需要编写构造函数;拷贝构造函数;析构函数;运算符重载=;
【一】传统写法:该开辟空间,开辟空间;该释放空间,释放空间;
可读性高,符合人的思维;
#define _CRT_SECURE_NO_WARNINGS 1#include<iostream>#include<assert.h>using namespace std;class String{public: friend ostream& operator<<(ostream& os, const String& s); String( const char* str = "") :_str(new char[strlen(str)+1]) { strcpy(_str, str); } String(const String& s) :_str(new char[strlen(s._str)+1]) { strcpy(_str, s._str); } String& operator=(const String&s) { if (_str != s._str) { // delete[] _str; //先释放_str,再申请空间如果申请不到, //_str = new char[strlen(s._str)+1]; //还毁坏了原有数据,得不偿失 //strcpy(_str, s._str); char* tmp = new char[strlen(s._str) + 1]; strcpy(tmp, s._str); delete[]_str; _str = tmp; } return *this; } ~String() { if (_str != NULL) { delete[]_str; _str = NULL; } }private: char* _str;};ostream& operator<<(ostream& os, const String& s){ os << s._str; return os;}int main(){ String s1("abcdefg"); String s2(s1); String s3 ; s3 = s2; cout << s2 << endl; cout << s3 << endl; return 0;}
【二】现代写法:建立一个中间对象tmp,出了这个作用域tmp会自动调用析构函数,代码简洁;
#define _CRT_SECURE_NO_WARNINGS 1#include<iostream>#include<assert.h>using namespace std;class String{public: friend ostream& operator<<(ostream& os, const String& s); String( const char* str = "") :_str(new char[strlen(str)+1]) { strcpy(_str, str); } String(const String& s) :_str(NULL) { String tmp(s._str); swap(_str, tmp._str); } /*String& operator=(const String& s) { if (this != &s) //这种在函数里边调用 { //拷贝构造函数产生临时变量 String tmp(s);//不如直接采用值传递方便 swap(_str, tmp._str); } return *this; }*/ String& operator=(String s) { swap(_str, s._str); return *this; } ~String() { if (_str != NULL) { delete[]_str; _str = NULL; } }private: char* _str;};ostream& operator<<(ostream& os, const String& s){ os << s._str; return os;}int main(){ String s1("abcdefg"); String s2(s1); String s3 ; s3 = s2; cout << s1 << endl; cout << s2 << endl; cout << s3 << endl; return 0;}
如下图所示对现代写法的tmp进行描述:
0 0
- C++面试题模拟实现String
- 【C++】面试题:模拟实现string类(版本一:用深度拷贝来实现 )
- c string 面试题
- 【C语言】【面试题】【笔试题】模拟实现strstr函数
- 【C语言】【面试题】【笔试题】模拟实现strncmp
- 【C语言】【面试题】【笔试题】模拟实现strncpy
- C++:模拟实现string类
- 模拟实现string类(c++)
- 【C++】模拟实现String类
- 面试题atoi的模拟实现
- 面试题:模拟实现strcpy函数
- 面试题:模拟实现strcat函数
- C++面试题-String函数实现
- C++面试题-String函数实现
- C++面试题:String类的实现
- C++面试题--string类的实现
- C++面试题:String类的实现
- C++面试题:String类的实现
- 【git】-git的特点
- 分辨服务器是linux系统还是Windows系统
- Java中分布式案例的实现方法
- next_permutation
- jeesite快速开发平台(二)---环境搭建
- C++面试题模拟实现String
- 从开机到加载操作系统计算机究竟干了啥?
- 『 Hello World 』By Blog
- TP 框架 常识
- spring与struts2整合案例
- Java调用本地接口:java.lang.UnsatisfiedLinkError
- Python 环境搭建(Mac OS)
- Lucene快速开发
- mysql中文乱码问题