雕刻时光

just do it……nothing impossible
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

string类的简要实现

Posted on 2013-12-05 19:35  huhuuu  阅读(236)  评论(0编辑  收藏  举报
#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='\0';
    }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\n",a.getString());
    
    a+=a;
    printf("%s\n",a.getString());

}

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

重载的写法

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