自定义string

自定义string:MyString

#include<iostream>
#include<string>
using namespace std;

class MyString
{
public:
    MyString()
    {
        // 默认构造函数将MyString初始化为空字符串"",而不是NULL
        m_pData = new char[1];
        if(m_pData == NULL)
        {
            cout << "allocation error" << endl;
            exit(1);
        }
        m_pData[0] = '\0';
        m_size = 0;

        cout << "MyString()" << endl;
    }

    MyString(const char *pData)
    {
        int len = strlen(pData);
        m_pData = new char[len+1];

        if(m_pData == NULL)
        {
            cout << "allocation error" << endl;
            exit(1);
        }

        strcpy(m_pData,pData);
        m_size = len;

        cout << "MyString(const char *pData)" << endl;
    }

    MyString(const MyString &mystring)
    {
        int len = strlen(mystring.m_pData);
        m_pData = new char[len+1];
        if(m_pData == NULL)
        {
            cout << "allocation error" << endl;
            exit(1);
        }
        strcpy(m_pData, mystring.m_pData);
        m_size = len;

        cout << "copy constructor" << endl;
    }

    MyString & operator=(const MyString &mystring)
    {
        if(&mystring != this)
        {
            int len = strlen(mystring.m_pData);
            char *pData = new char[len+1];

            if(pData == NULL)
            {
                cout << "allocation error" << endl;
                exit(1);
            }

            strcpy(pData, mystring.m_pData);
            delete []m_pData;
            m_pData = pData;
            m_size = len;
        }

        cout << "operator=" << endl;
        return *this;
    }

    ~MyString()
    {
        delete [] m_pData;
        cout << "~MyString()" << endl;
    }
private:
    int m_size;
    char *m_pData;
};

int main(void)
{
    MyString stra;
    MyString strb("ssss");
    MyString strc(stra);
    stra = strb;

    // 输出
    //MyString()
    //MyString(const char *pData)
    //copy constructor
    //operator=
    //~MyString()
    //~MyString()
    //~MyString()
    return 0;
}

 

posted on 2013-09-19 23:55  江在路上2  阅读(160)  评论(0编辑  收藏  举报