C++:面试时应该实现的string类(构造函数、拷贝构造函数、赋值运算符重载和析构函数)

一、string类的4个基本函数是什么?

构造函数
拷贝构造函数
赋值运算符重载
析构函数

二、函数实现

1.构造函数

String(char* pStr = " ")
    {
        if (NULL == pStr)
        {
            _pStr = new char[1];
            *_pStr = '\0';
        }
        else
        {
            _pStr = new char[strlen(pStr) + 1];
            strcpy(_pStr, pStr);
        }
    }

2.拷贝构造函数

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

3.赋值运算符重载

String&operator=(const String& s)
    {
        if (this != &s)
        {
            char*pTemp = new char[strlen(s._pStr) + 1];
            strcpy(pTemp, s._pStr);
            delete[] _pStr;
            _pStr = pTemp;
        }
        return *this;
    }

4.析构函数

~String()
    {
        if (_pStr)
        {
            delete[] _pStr;
        }
    }

三、完整类的实现

class String
{
public:
    //构造函数
    String(char* pStr = " ")
    {
        if (NULL == pStr)
        {
            _pStr = new char[1];
            *_pStr = '\0';
        }
        else
        {
            _pStr = new char[strlen(pStr) + 1];
            strcpy(_pStr, pStr);
        }
    }
    //拷贝构造函数
    String(const String&s)
        :_pStr(new char[strlen(s._pStr) + 1])
    {
        strcpy(_pStr, s._pStr);
    }
    //赋值运算符重载
    String&operator=(const String& s)
    {
        if (this != &s)
        {
            char*pTemp = new char[strlen(s._pStr) + 1];
            strcpy(pTemp, s._pStr);
            delete[] _pStr;
            _pStr = pTemp;
        }
        return *this;
    }
    //析构函数
    ~String()
    {
        if (_pStr)
        {
            delete[] _pStr;
        }
    }
private:
    char* _pStr;
};

猜你喜欢

转载自blog.csdn.net/dangzhangjing97/article/details/81590049