String类实现

来源:互联网 发布:网络小说家怎么赚钱 编辑:程序博客网 时间:2024/06/03 17:43
class String{//    friend ostream& operator<<(ostream&,String&);//    friend istream& operator>>(ostream&,String&);public:    String(const char *str=NULL);    String(const String& other);    ~String();    String& operator=(const String& other);    String operator+(const String& other)const;    bool operator==(const String& other);    char &operator[](unsigned int);    size_t size(){return strlen(m_data);}private:    char *m_data;};inline String::String(const char*str){    if(str==NULL)        m_data=NULL;    else    {        m_data=new char[strlen(str)+1];        strcpy(m_data,str);    }}inline String::String(const String& other){    if(other.m_data==NULL)        m_data=NULL;    else{        m_data=new char[strlen(other.m_data)+1];        strcpy(m_data,other.m_data);    }}inline String& String::operator=(const String& other){    if(this!=&other){        delete[] m_data;        if(other.m_data==NULL)            m_data=NULL;        else{            m_data=new char[strlen(other.m_data)+1];            strcpy(m_data,other.m_data);        }    }    return *this;}inline String String::operator+(const String& other)const {    String newString;    if(other.m_data==NULL)        newString=*this;    else if(m_data==NULL)        newString=other;    else{        newString.m_data=new char[strlen(m_data)+strlen(other.m_data)+1];        strcpy(newString.m_data,m_data);        strcpy(newString.m_data,other.m_data);    }    return newString;}inline bool String::operator==(const String& other){    if(strlen(other.m_data) != strlen(m_data))        return false;    return strcmp(m_data,other.m_data)?true:false;}inline char& String::operator[](unsigned int index){    if(index<=strlen(m_data))        return m_data[index];}//ostream& operator>>(ostream &os,String &str){//    os<<str.m_data;//    return os;//}//istream& operator<<(istream& input,String& str){//    char tmp[255];//    input>>setw(255)>>tmp;//    str=tmp;//    return input;//}