String类实现

来源:互联网 发布:紫峰秒杀软件 编辑:程序博客网 时间:2024/06/16 04:02
#include <iostream>#include <cstring>#include <assert.h>using namespace std;class String{public:String(){char *m_pstr = new char[1];m_pstr[0] = '\0';}String(const char *pstr){assert(pstr != NULL);m_pstr = new char[strlen(pstr) + 1];strcpy(m_pstr, pstr);}String(const String & rhs){m_pstr = new char[strlen(rhs.m_pstr) + 1];strcpy(m_pstr, rhs.m_pstr);}~String(){delete[]m_pstr;m_pstr = NULL;}String & operator=(const String  & rhs){if (this != &rhs){delete[] m_pstr;m_pstr = new char[strlen(rhs.m_pstr) + 1];strcpy(m_pstr, rhs.m_pstr);}return *this;}String operator+(const String &rhs) const{String newString;if (!rhs.m_pstr)newString = *this;else if (!m_pstr)newString = rhs;else{newString.m_pstr = new char[strlen(m_pstr) + strlen(rhs.m_pstr) + 1];strcpy(newString.m_pstr, m_pstr);strcat(newString.m_pstr, rhs.m_pstr);}return newString;}char operator [](const unsigned int index){if (index >= 0 && index<strlen(m_pstr))return m_pstr[index];else{cout << "Error: the index of [] is invalid." << endl;exit(0);}}friend ostream& operator<<(ostream & output, const String &rhs) {output << rhs.m_pstr;return output;}friend istream& operator>>(istream& is, String& rhs){char temp[255];is >> temp;rhs = temp;return is;}bool operator==(const String& rhs){if (strlen(m_pstr) != strlen(rhs.m_pstr))return false;elsereturn strcmp(m_pstr,rhs.m_pstr) ? false : true;}size_t size() const{return strlen(m_pstr);}const char* c_str() const{return m_pstr;}private:char *m_pstr;};

0 0
原创粉丝点击