String类练习

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

class String
{
public:
    String(const char* str = NULL)
    {
        m_data = strcpy(new char[strlen(str?str:"")+1],str?str:"");
    }
    ~String()
    {
        if(m_data)
            delete[] m_data;
    }
    String(const String& that)
    {
        m_data=strcpy(new char[strlen(that.m_data)+1],that.m_data);
    }

    String& operator=(const String& that)
    {
        if(&that != this)
        {
            //初级
            //delete[] m_data;
            //m_data = strcpy(new char[strlen(that.m_data)+1],that.m_data);

            //中级
            //char* temp = new char[strlen(that.m_data)+1]);//如果分配失败,会抛出异常,不会执行下面代码
            //delete[] m_data;
            //m_data = strcpy(temp,that.m_data);

            //高级
            String str(that);
            swap(m_data,str.m_data); //实现代码复用
        }
        return *this;
    }

    char* c_str() const
    {
        return m_data;
    }
private:
    char* m_data;
};

int main()
{
    String s1("Hello Word");
    cout << s1.c_str() << endl;
    String s2(s1);
    cout << s2.c_str() << endl;
    return 0;

}

posted on 2013-12-27 10:02  Sam.Richard  阅读(378)  评论(0编辑  收藏  举报

导航