码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-02 15:39:25      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

 

 

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

 

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

标签:

原文地址:http://www.cnblogs.com/diegodu/p/4616120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!