C++:面接時に実装すべきstringクラス(コンストラクション関数、コピーコンストラクション関数、付与演算子リロードおよび構造解析関数)

4548 ワード

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