您的位置:首页 > 编程语言 > C语言/C++

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++
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string c++