• string类的简要实现


    #include<iostream>
    #include<cstring>
    #include<cstdlib>
    #include<cstdio>
    #include<algorithm>
    using namespace std;
    
    class mystring{
    public:
        mystring(const char *str=NULL);
        mystring(const mystring &other);
        ~mystring(void);
        mystring &operator=(const mystring &other);
        mystring &operator+=(const mystring &other);
    
        char *getString();
    private:
        char *m_data;
    };
    
    //普通构造函数
    mystring::mystring(const char *str){
        if(str==NULL){
            m_data=new char;
            *m_data='';
        }else{
            int lenth=strlen(str);
            m_data=new char[lenth+1];
            strcpy(m_data,str);
        }
    }
    
    mystring::~mystring(void){
        delete[]m_data;//m_data是内部数据类型,也可以写成delete m_data
    }
    
    //拷贝构造函数
    mystring::mystring(const mystring &other){
        //允许操作other的私有成员m_data???
        int lenth=strlen(other.m_data);
        m_data=new char [lenth+1];
        strcpy(m_data,other.m_data);
    
    }
    
    //赋值函数
    mystring &mystring::operator=(const mystring &other){
        
        //1.检测自赋值 处理 a=a的情况
        if(this==&other){
            return *this;
        }
    
        //2释放原有的内存
        delete []m_data;
    
        //3分配新的内存资源,并复制内容
        int lenth=strlen(other.m_data);
        m_data=new char[lenth+1];
        strcpy(m_data,other.m_data);
    
        //4返回本对象的引用
        return *this;
    }
    
    //赋值函数
    mystring &mystring::operator+=(const mystring &other){
    
        int left_lenth=strlen(m_data);
        int right_lenth=strlen(other.m_data);
    
        //1分配新的内存资源,并复制内容
        char *temp_data=new char[left_lenth+right_lenth+1];
        strcpy(temp_data,m_data);
        strcat(temp_data,other.m_data);
        delete []m_data;//2释放原有的内存
    
        m_data=temp_data;
    
        //3返回本对象的引用
        return *this;
    }
    
    char * mystring::getString(){
        return m_data;
    }
    
    int main()
    {
        mystring a=mystring("123456");
        mystring b=mystring(a);
        mystring c=mystring("666666");
        mystring d;
        d=c;
    
        a+=d;
        printf("%s
    ",a.getString());
        
        a+=a;
        printf("%s
    ",a.getString());
    
    }

    注意构造函数,拷贝构造函数,赋值函数,析构函数的写法

    重载的写法

    参考:高质量C++C 编程指南

  • 相关阅读:
    Leetcode——栈和队列(3)
    Leetcode——栈和队列(2)
    java——面试题 基础(上)
    Leetcode——栈和队列(1)
    LeetCode——动态规划整理(2)
    LeetCode——动态规划整理(1)
    计算机网络——数据中心(下)
    计算机网络——数据中心(上)
    计算机网络——HTTP(下)
    计算机网络——HTTP(上)
  • 原文地址:https://www.cnblogs.com/huhuuu/p/3460240.html
Copyright © 2020-2023  润新知