类中的特殊内容
仿照string类,自己手动实现 My_string
#include <iostream>
#include <string.h>
using namespace std;class My_string
{
private:int len;int size;char *ptr;
public:My_string():size(15),len(0){ptr=new char[size];ptr[0]='\0';}My_string(const char *src){len = strlen(src);ptr = new char[len+1];strcpy(ptr,src);}My_string(const My_string& other):ptr(new char[this->len]),len(other.len){len = other.len;size = other.size;ptr = new char[size];strcpy(ptr,other.ptr);}//拷贝赋值My_string& operator=(const My_string& other){if(this!=&other){delete[]ptr;len = other.len;size = other.size;ptr = new char[size];strcpy(ptr,other.ptr);}return *this;}//析构函数~My_string(){delete[]ptr;}//判空bool empty(){return this->len==0;}//尾插void push_back(char x){if(this->len==this->size-1){return ;}this->ptr[len++]=x;}//尾删void dele_back(){if(this->len==0){return ;}this->ptr[len-1]=this->ptr[len];this->len--;}//at函数实现char &at(int x){if(x>=0&&x<size){return ptr[x];}else{cout<<"超出范围"<<endl;exit(1);}}//清空函数void dele_empty(){for(int i=0;i<this->len;i++){dele_back();}}//返回C风格字符串char *my_ptr(){return this->ptr;}//返回实际长度int my_len(){return this->len;}//返回当前最大容量int my_size(){return this->size;}//二倍扩容void doubledilatation(){//char *ptr1=new char[size];//*ptr1=*this->ptr;// if(this->len==this->size)// {// this->size*=2;// }// cout <<" len="<<len<<" size="<<size<<endl;size *= 2;char *new_ptr = new char[size];strcpy(new_ptr, ptr);delete[] ptr;ptr = new_ptr;}void show(){cout <<"len="<<len<<" size="<<size<<" ptr="<<ptr<<endl;}
};int main()
{My_string s1;My_string s2("lili");My_string s3("lililyq");My_string s4(s2);My_string s5(s2);s2.push_back('y');s2.show();s2.dele_back();s2.show();cout<<"第一个字符:"<<s2.at(2)<<endl;cout<<s2.my_ptr()<<endl;cout<<s2.my_len()<<endl;cout<<s2.my_size()<<endl;//while(1)// {// s2.doubledilatation();//}return 0;
}