简单实现C++库中的String类

#include <iostream>
#include <string.h>
#pragma warning(disable: 4996)
using namespace std;

class String
{
    friend ostream& operator<<(ostream& os, String& str);

public:
    String(char* str = "")
        : _str(new char[strlen(str)+1])
    {
        strcpy(_str, str);
    }

    String(const String& s)
        :_str(new char[strlen(s._str) + 1])
    {
        strcpy(_str, s._str);
    }

    String& operator=(const String& s)
    {
        if (_str != s._str)
        {
            String sTmp(s);

            char* pTmp = sTmp._str;
            sTmp._str = _str;//将当前对象的空间交给tmp,让其调用析构函数释放该空间
            _str = pTmp;
        }

        return *this;
    }

    char& operator[](size_t index)
    {
        return _str[index];
    }

    const char& operator[](size_t index)const//[]操作符必须成对重载
    {
        return _str[index];
    }

    ~String()
    {
        if (_str != NULL)
        {
            delete[] _str;
            _str = NULL;
        }
    }
private:
    char* _str;
};

ostream& operator<<(ostream& os, String& str)
{
    os << str._str;
    return os;
}


int main()
{
    String s1;
    String s2("hello");
    String s3(s2);

    String s4("world");

    s4 = s3;

    cout << s4[5] << endl;
    cout << s4 << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/virgofarm/article/details/81144088