zoukankan      html  css  js  c++  java
  • 从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 = '';
            }
            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 Êǽöº¬¡®¡¯µÄ×Ö·û´® 
        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;
    }
  • 相关阅读:
    Linux系统安全及应用
    Linux 10 进程和计划的管理任务
    Centos netdata 的安装及配置
    Centos nmon安装及使用
    Python 各种数据类型的了解(上)
    神奇的循环知识
    Pathon的基础知识
    初次遇见Python
    操作系统与编程语言的简介
    计算机硬件基础
  • 原文地址:https://www.cnblogs.com/diegodu/p/4616120.html
Copyright © 2011-2022 走看看