首页 > 编程语言 > 详细

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

时间:2016-01-24 19:51:14      阅读:144      评论:0      收藏:0      [点我收藏+]
#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;
}


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

原文:http://10740184.blog.51cto.com/10730184/1738017

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!