C++ string 类的简单实现
2016-09-23 10:07
260 查看
class String{ char* ptr; size_t len; public: String():ptr(nullptr),len(1){} String(const char* str){ len = strlen(str); ptr = new char[++len];// last one is '\0' strcpy(ptr,str); } String(const String& str){ if(ptr != nullptr){ delete [] ptr; } len = str.len; ptr = new char[len]; strcpy(ptr,str.ptr); } String& operator=(const String& str){ if(ptr == str.ptr) //self assignment return *this; if(ptr != nullptr) delete[] ptr; len = str.len; ptr = new char[len]; strcpy(ptr,str.ptr); return *this; } size_t size()const { return len-1; } int empty()const { return size() == 0; } String operator+=(const String& str){ *this= *this+str; return *this; } void swap(String &str){ using std::swap; swap(str.ptr,ptr); swap(len,str.len); } String operator+(const String& str){ if(str.empty()) return *this; int newlen = size() + str.size()+ 1; len= newlen; char* tptr = new char[newlen]; strcat(tptr,ptr); strcat(tptr,str.ptr); return String(tptr); } bool operator==(const String& str){ return strcmp(str.ptr,ptr)==0; } friend ostream& operator<<(ostream & os,const String& str){ os << str.ptr; return os; } ~String(){ if(ptr != nullptr) delete[] ptr; } };
需要注意的是,在自我赋值的时候,需要保存原来的内存空间。参见effective c++
相关文章推荐
- C++ string和map容器实现简单的英文翻译
- c++ String 类的简单实现和写时拷贝
- C++ string类简单实现
- C++ String类简单实现
- C++ string 简单实现
- c++ string的一些常用函数的源码以及string的简单实现
- C++ String 类的简单实现
- 简单的在线升级的实现方法
- 用vb.net与acess结合实现简单的电话号码本程序(一)
- 简单实现Crystal Report的动态加载
- 跨域名的Cookie实现---简单另类的实现方法
- 用NUnit2.1简单实现.net的测试驱动开发(TDD)
- 图像分割的一些简单实现
- 内容分页简单实现代码及祥解(C#)
- Dhtml+Js算法:5个小球运动的简化版,变通实现更简单的飞行的图片
- 打印的简单实现,以及更改打印设置
- Editplus + Zend Encoder实现简单PHP源码加密IDE环境
- ATL实现Connection Point的一种简单的方法
- http断点续传简单实现(java)
- 自己如何实现简单的http服务器