从String类看写C++ class需要注意的地方

 

 

#include <iostream>
#include <string.h>

using namespace std;

class String
{
    char* m_data;
public:
    String(const char* p = NULL)
    {
        if(p == NULL)
        {
            m_data = new char[1];
            *m_data = '\0';
        }
        else
        {
            m_data = new char[strlen(p) + 1];
            strcpy(m_data, p);
        }
    }

    String(const String & other)
    {
        if(&other != this)
        {
            //delete [] m_data; //¹¹Ô캯ÊýÖв»ÐèÒªdelete momory:w
            m_data = new char[strlen(other.m_data) + 1];
            strcpy(m_data, other.m_data);
        }
    }

    ~String()
    {
        delete [] m_data;
    }

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

    }
    friend String operator+(const String &s1, const String &s2);
    friend inline ostream & operator << (ostream & os, String &str);

};

String operator+(const String &s1, const String &s2)
{
    String temp;
    delete [] temp.m_data;  // temp.data Êǽöº¬¡®\0¡¯µÄ×Ö·û´® 
    temp.m_data = new char[strlen(s1.m_data) + strlen(s2.m_data) +1];
    strcpy(temp.m_data, s1.m_data);
    strcat(temp.m_data, s2.m_data);
    return temp;
}

ostream & operator << (ostream & os, String &str)
{
    os  << str.m_data << endl;
    return os;
}

int main()
{
    String str1("abc");
    cout << str1;

    String str2(str1);
    cout << str2;

    String str3;
    cout << str2;
    str3 = str2;

    String str4("def");

    String str5;
    str5 = str3 + str4;
    cout << str5;
}

 

posted @ 2015-07-02 15:02  穆穆兔兔  阅读(525)  评论(0编辑  收藏  举报