string 简单实现

来源:互联网 发布:农村淘宝黄岩服务中心 编辑:程序博客网 时间:2024/05/21 22:44
namespace ss{    class string {        friend ostream& operator <<(ostream&, const string&);        char *_str;    public:        string():_str(new char[1]){            _str[0] = '\0';        }        string(const char* str):_str(new char[strlen(str)+1]) {            strcpy(_str, str);        }        string(const string & s):_str(new char[s.size()+1]){            strcpy(_str, s._str);        }        string( string&& s):_str(s._str) {            s._str = nullptr;        }        //operator        string & operator =(string s) {            swap(s);            return *this;        }        char & operator [](int i) {return _str[i];}        /*         string &operator =(const string &s){         if (this != &s) {         delete []_str;         if(s._str!= nullptr) {         _str = new char[strlen(s._str)+1];         strcpy(_str, s._str);         }         }         return *this;         }*/        //get        size_t size() const {            return strlen(_str);        }        //        void swap(string& s) {            std::swap(_str, s._str);        }    };    ostream& operator << (ostream& os, const string &ob)    {        os << ob._str;        return os;    }    };

0 0
原创粉丝点击