自定义实现String类的内容 直接在代码中阐述:附有测试样例 代码:
#include //#include using namespace std; class String { public: //ctor String(); String(const char* s); String(const char* s, size_t len); String(const String& rhs); String(size_t Len); String& operator=(const String& rhs); //dtor ~String(); //get size_t size() const; const char* data() const; const char* c_str() const; // set & get char & operator[](size_t index); char operator[] (size_t index) const; //imp String operator +(const String& rhs); void operator +=(const String& rhs); //输出 friend ostream& operator <<(ostream& out,const String& rhs); private: char* data_; size_t len_; }; String::String() : data_(NULL), len_(0) { data_ = new char[1]; data_[0] = ‘\0‘; } String::String(size_t Len) { data_ = new char[Len+1]; for(size_t i=0;i<=Len;i++) { data_[i] = ‘\0‘; } } String::String( const char* s ) { size_t i = 0; size_t len = 0; while(s[i] != ‘\0‘) { i++; len++; } data_ = new char[len+1]; for(size_t j = 0;j ‘\0‘; len_ = len; } String::String( const char* s, size_t len ) { data_ = new char[len+1]; for(size_t k=0;k‘\0‘; len_ = len; } String::String( const String& rhs ) { size_t len = rhs.size(); data_ = new char[len+1]; for(size_t i=0;i‘\0‘; len_ = len; } String String::operator +(const String& rhs) { size_t totalLen = len_ + rhs.len_; String tmp(totalLen); size_t i,j; for(i=0;ifor(j=0;jreturn tmp; } void String::operator +=(const String& rhs) { size_t totalLen = len_ + rhs.len_; String tmp(totalLen); size_t i,j; for(i=0;ifor(j=0;jthis = tmp; } String& String::operator=( const String& rhs ) { //比较对象的地址 if(this == &rhs) { return *this; } delete[] data_; size_t len = rhs.size(); data_ = new char[len+1]; for(size_t i = 0;i ‘\0‘; return *this; } String::~String() { if(data_) { delete[] data_; data_ = NULL; } len_ = 0; } size_t String::size() const { int i = 0; int len_ = 0; while(data_[i] != ‘\0‘) { i++; len_++; } return len_; } const char* String::data() const { return data_; } const char* String::c_str() const { return data_; } char & String::operator[](size_t index ) { if(index > len_) { return data_[len_-1]; } else { return data_[index]; } } char String::operator[] (size_t index) const { if(index > len_) { return data_[len_-1]; } else { return data_[index]; } } //注意 友员不是成员函数 不用加上String:: ostream& operator <<(ostream& out,const String& rhs) { out<return out; } int main() { String a("hello",3); cout <String b("world"); String c(b); cout <2] <//cout < //cout < /* String a("hello"); cout < }
自定义实现String类