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]