C++:【常见面试题】String类的写法

来源:互联网 发布:陶哲轩智商知乎 编辑:程序博客网 时间:2024/06/05 09:50
#include<iostream>#include<stdlib.h>using namespace std;class String{public:    String(const char* str)        :_str(new char[strlen(str) + 1])  //  \0    {        strcpy(_str, str);    }    String(const String& s)         :_str(NULL)   //若不赋空则为随机值,随机值_str析构函数释放指针会崩溃    {        String tmp(s._str);     //重新开辟空间        swap(_str, tmp._str);    }    //String& operator = (const String& s)    //{    //    if (this != &s) //不是自己给自己赋值    //    {    //        String tmp(s._str);   //重新开辟空间    //        swap(_str, tmp._str);    //    }    //    return *this;    //}    String& operator = (String s)    {        swap(_str, s._str);        return *this;    }    ~String()    {        if (_str)        {            delete[] _str;    //注意与new char[n]匹配        }    }    char* CStr()    {        return _str;    }    char& operator[](size_t index)  //重载输出单个字符    {        return _str[index];    }private:    char* _str;};void Test2(){    String s("change world");    cout << s[1] << endl;    s[1] = 'x';    cout << s.CStr() << endl;}int main(){    Test2();    system("pause");    return 0;}


0 0
原创粉丝点击