#include <iostream>
#include <cstring>
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;
cout<<"无参构造"<<endl;
}
int strlen(const char * src)
{
int count = 0;
for(int i = 0;src[i]!='\0';i++)
{
count++;
}
return count;
}
//有参构造
My_string(const char *src) : size(15), len(strlen(src))
{
this->ptr = new char[size];
strcpy(this->ptr, src); // 使用 strcpy 复制字符串
cout << "有参字符串构造: " << ptr << endl;
}
//有参构造
My_string(int num, char value) : size(15), len(num)
{
this->ptr = new char[size];
for (int i = 0; i < num; i++) {
this->ptr[i] = value;
}
this->ptr[num] = '\0';
cout << "有参构造: " << ptr << endl;
}
//拷贝构造
My_string(const My_string &other) : size(other.size), len(other.len)
{
this->ptr = new char[size];
strcpy(this->ptr, other.ptr);
}
//拷贝赋值
My_string &operator=(const My_string &other)
{
if (this != &other) {
delete[] this->ptr;
this->size = other.size;
this->len = other.len;
this->ptr = new char[size];
strcpy(this->ptr, other.ptr);
}
return *this;
}
//析构函数
~My_string(){}
//判空
bool empty()
{
return len==0;
}
//尾插
void push_back(char value)
{
if (len + 1 >= size)
{
resize(); // 如果容量不足,扩容
}
cout<<"len = "<<len<<endl;
this->ptr[len]=value;
this->ptr[len+1]='\0';
this->len++;
}
//尾删
void pop_back()
{
if(!empty())
{
this->ptr[len-1]='\0';
this->len--;
}
}
//at函数实现
char &at(int index)
{ if(index<len)
{
return ptr[index-1];
}
else
{
throw std::invalid_argument("位置错误");
}
}
//清空
void clear()
{
if (this->ptr != NULL)
{
delete this->ptr;
this->ptr = NULL;
this->len=0;
this->size = 15;
}
}
//c语言格式输出
char *data()
{
return this->ptr;
}
//求字符串长度
int get_length()
{
return this->len;
}
//求最大容量
int get_size()
{
return this->size;
}
//君子函数:二倍扩容
void resize()
{
this->size *= 2;
char * newData = new char[size];
strcpy(newData,this->ptr);
delete [] this->ptr;
this->ptr = newData;
}
//show
void show()
{
for(int i = 0;i<len;i++)
{
cout<<this->ptr[i]<<" ";
}
cout<<endl;
}
};
int main()
{
My_string s1;
My_string s2("hello");
My_string s3(5,'A');
s1.show();
s2.show();
s3.show();
cout<<s3.data()<<endl;
cout<<"s2.get_length = "<<s2.get_length()<<endl;
cout<<"s3.get_size = "<<s3.get_size()<<endl;
s2.resize();
cout<<"s2.resize()后,s2.get_size = "<<s2.get_size()<<endl;
cout<<"s2的第2位"<<s2.at(2)<<endl;
s2.push_back('W');
s2.push_back('O');
s2.push_back('R');
s2.push_back('L');
s2.push_back('D');
s3.pop_back();
s2.show();
s3.show();
return 0;
}
c++类中的特殊函数及关键字
最新推荐文章于 2024-09-27 11:26:03 发布