string 简单实现

namespace ss{
    class string {
        friend ostream& operator <<(ostream&, const string&);
        char *_str;
    public:
        string():_str(new char[1]){
            _str[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;
    }
    
};

原文地址:https://www.cnblogs.com/cxchanpin/p/7059656.html