#include <iostream>
using namespace std;
class My_string
{
private:
char *ptr; //指向字符数组的指针
int size; //字符串的最大容量
int len; //字符串当前容量
public:
//无参构造
My_string():size(15)
{
this->ptr = new char[size];
this->ptr[0] = '\0'; //表示串为空串
this->len = 0;
}
//有参构造
My_string(const char* src):size(15),len(sizeof("helloworld")),ptr(new char)
{
cout<<"My_class::有参构造"<<endl;
};
My_string(int num, char value):size(15),len(num),ptr(new char)
{
for(int i=0;i<num;i++)
{
*(this->ptr+i) = value;
}
*(this->ptr+num)='\0';
cout<<"My_class::有参构造"<<endl;
};
//拷贝构造
My_string (const My_string &other):ptr(other.ptr),size(other.size),len(other.len)
{
cout<<"My_string::拷贝构造函数"<<endl;
};
//拷贝赋值
My_string & operator=(const My_string &other)
{
if(this != &other)
{
this->ptr = other.ptr;
this->size = other.size;
this->len = other.len;
}
cout<<"My_string::拷贝赋值函数"<<endl;
return *this;
};
//析构函数
~My_string()
{
delete ptr;
cout<<"My_string::析构函数,this = "<<this<<endl;
};
//判空
bool MYempty() const
{
return this->ptr == nullptr || this->len == 0; // 如果指针为空或长度为0,则认为是空
};
//尾插
void push_back(char value)
{
this->size++;
this->ptr[len] = value;
this->len++;
this->ptr[size] = 0;
};
//尾删
void pop_back()
{
this->ptr[len-1] = 0;
this->size--;
this->len--;
};
//at函数实现
char &at(int index)
{
static char num;
num = this->ptr[index-1];
return num;
};
//清空函数
void clear()
{
this->size = 15;
delete[] ptr;
this->ptr = new char[1];
this->ptr[0] = '\0';
this->len = 0;
};
//返回C风格字符串
char *data()
{
return ptr;
};
//返回实际长度
int get_length()
{
return this->len;
};
//返回当前最大容量
int get_size()
{
return this->size;
};
//君子函数:二倍扩容
//展示函数
void show()
{
cout<<"ptr = "<<ptr<<endl;
cout<<"size = "<<size<<endl;
cout<<"len = "<<len<<endl;
}
};
int main()
{
My_string s;
s.show();
cout<<"***************************************"<<endl;
My_string s1("helloworld");
s1.show();
My_string s2(5,'A');
s2.show();
cout<<"***************************************"<<endl;
My_string s3=s2;
s3.show();
cout<<"***************************************"<<endl;
s = s2;
s.show();
cout<<"***************************************"<<endl;
s.push_back('B');
s.show();
return 0;
}
9.23C++(day4)
最新推荐文章于 2024-09-26 12:00:11 发布