c++自定义String

mystring.c

#include "mystring.h"
#define SIZE 8
#include"mystring.h"
//计算所需最小满足len的容量 每次都是8的倍数
int max_size(int len,int maxsize){
   

    while(len>maxsize){
   
        maxsize*=2;
    }
    return maxsize;
}
//构造函数
mystring::mystring(){
   
    //初始化
    size=0;
    maxsize=SIZE;
    str=new char[size];
    cout<<"无参构造"<<endl;
}
//有参构造
mystring::mystring(const char * str1){
   
    //初始化
     size=strlen(str1);
    maxsize=max_size(size+1,SIZE);//计算出最小满足len的容量 需要考虑'\0'
    str=new char[maxsize];
    //拷贝
    memcpy(str,str1,size+1);//需要考虑'\0'
    cout<<"mystring::有参"<<endl;

}
mystring::mystring(int n,char ch){
   
    maxsize=max_size(n+1,SIZE);//\0
    size=n;
    str=new char[maxsize];
    int i=0;
    for(i=0;i<size;i++){
   
        str[i]=ch;
    }
    str[i]='\0';

}
//析构函数
mystring::~mystring(){
   
    delete []str;
    cout<<"析构"<<endl;
}
//拷贝构造函数
mystring ::mystring(const mystring &other){
   
    //初始化
    if(other.str==NULL){
   return ;}
    size=other.size;
    maxsize=other.maxsize;
    str=new char[maxsize];
    //拷贝
    memcpy(str,other.str,maxsize);
    cout<<"拷贝构造函数"<<endl;
}


//拷贝赋值函数
mystring & mystring::operator=(const mystring &other){
   
    size=other.size;
    maxsize=other.maxsize;
    delete []str;
    str=new char[maxsize];
    memcpy(str,other.str,maxsize);
    cout<<"拷贝赋值函数"<<endl;
    return *this;
}
mystring & mystring::operator=(const char * str1){
   
    //初始化
     size=strlen(str1);
     maxsize=SIZE;
    maxsize=max_size(size+1,maxsize);
    str=new char[maxsize]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值