1. 程式人生 > >C++:面試時應該實現的string類(建構函式、拷貝建構函式、賦值運算子過載和解構函式)

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; };