C++:类中的特殊内容
仿照string类,自己手动实现 My_string
1.主函数
#include <iostream>#include "my_string.h"using namespace std;int main()
{My_string s1;s1.show();My_string s2("hello");s2.show();cout<<s2.at(3)<<endl;My_string s3(6,'G');s3.show();My_string s4=s2;s4.show();My_string s5;s5.operator=(s3);s5.show();s5.push_back('H');s5.show();s5.pop_back();s5.show();s5.clear();s5.show();return 0;
}
My_string.h
#ifndef MY_STRING_H
#define MY_STRING_H
#include <iostream>
#include <cstring>using namespace std;class My_string
{
private:char *ptr;int size;int len;
public://无参构造My_string();//有参构造My_string(const char *src);My_string(int num,char value);//拷贝构造My_string (const My_string & other):size(other.size),len(other.len){this->ptr = new char[size];for (int i = 0; i < this->len; i++){this->ptr[i] = other.ptr[i];}this->ptr[this->len] = '\0';//cout<<"拷贝构造"<<endl;}//拷贝赋值My_string & operator=(const My_string & other){if(this!=&other){this->size=other.size;this->len=other.len;this->ptr = new char[size];for(int i=0;i<len;i++){this->ptr[i]=other.ptr[i];}this->ptr[this->len] = '\0';}return *this;}//析构函数~My_string();//判空bool empty();//尾插void push_back(char value);//尾删void pop_back();//at函数;char at(int index);//清空函数void clear();//返回实际长度int get_length();//返回当前最大容量int get_size();//君子函数:二倍扩容void doubleCap();void show();};
#endif // MY_STRING_H
My_string.cpp
#include "my_string.h"My_string::My_string()
{size=15;this->ptr=new char[size];this->ptr[0]='\0';this->len=0;
}
//有参构造
My_string::My_string(const char *src)
{len=0;for(int i=0;src[i]!='\0';i++){len++;}size=len+1;this->ptr=new char[size];for(int i=0;i<len;i++){ptr[i]=src[i];}ptr[len]='\0';}My_string::My_string(int num,char value)
{
len=num;
size=len+1;
this->ptr=new char[size];
for(int i=0;i<len;i++)
{ptr[i]=value;
}
ptr[len]='\0';
}//析构函数
My_string::~My_string()
{delete []ptr;//cout<<"析构函数"<<this<<endl;
}
//判空
bool My_string::empty()
{return this->len==0;
}
//尾插
void My_string::push_back(char value)
{this->ptr[len]=value;len++;ptr[this->len] = '\0';
}//尾删
void My_string::pop_back()
{if(empty()){return;}ptr[len-1]='\0';len--;}//at函数
char My_string::at(int index)
{char num;num=ptr[index-1];return num;
}//清空函数
void My_string::clear()
{for(int i=0;i<len;i++){ptr[i]='\0';}this->size=0;this->len=0;
}//返回实际长度
int My_string::get_length()
{return len;
}
//返回当前最大容量
int My_string::get_size()
{return size;
}//君子函数:二倍扩容
void My_string::doubleCap()
{if(len>=size){size=size*2;char * new_ptr=new char[size];strcpy(new_ptr,ptr);delete ptr;ptr=new_ptr;}
}void My_string::show()
{cout<<"*ptr="<<ptr<<endl;cout<<"size="<<size<<endl;cout<<"len="<<len<<endl;
}