String类的实现

来源:互联网 发布:什么软件改变图片大小 编辑:程序博客网 时间:2024/06/06 03:21
class String{private:char *m_data;public:String(const char *str = NULL);//默认构造函数String(const String& other);//拷贝构造函数~String();//析构函数String &operator=(const String&other);//重载赋值运算符bool operator==(const String&other);//重载equals运算符String operator+(const String&other);//重载连接运算符char &operator[](int index);//重载下标访问运算符friend ostream& operator<<(ostream& out , const String& str);//重载输出运算符friend istream& operator>>(istream& in , String& str);//重载输入运算符size_t size()const{return strlen(m_data);}};String::String(const char *str){ if(NULL == str){ m_data = new char[1]; *m_data = '\0'; }else{ m_data = new char[strlen(str)+1]; strcpy(m_data , str); }}String::String(const String& other){m_data = new char[strlen(other.m_data)+1];strcpy(m_data , other.m_data);}String::~String(){delete []m_data;}String& String::operator=(const String&other){if(this != &other){if(NULL != m_data)delete []m_data;m_data = new char[strlen(other.m_data)+1];strcpy(m_data , other.m_data); }return *this;}bool String::operator==(const String&other){int len1 = this->size();int len2 = other.size();return strcmp(m_data , other.m_data)?false:true;}String String::operator+(const String&other){int len1 = this->size();int len2 = other.size();String newStr;newStr.m_data = new char[len1+len2+1];strcpy(newStr.m_data , m_data);strcat(newStr.m_data,other.m_data);return newStr;}char &String::operator[](int index){assert(index>=0 && index<this->size());return m_data[index];}ostream& operator<<(ostream& out , const String& str){out<<str.m_data;return out;}istream& operator>>(istream& in , String& str){char buffer[1024];char c;int i=0;while((c=in.get())!='\n'){buffer[i++] = c;}buffer[i] = '\0';if(NULL != str.m_data)delete []str.m_data;str.m_data = new char[i+1];strcpy(str.m_data , buffer);return in;}


0 0
原创粉丝点击