main.cpp
#include "My_string.h"
int main()
{
My_string s;
s.show();
cout << "************************"<<endl;
My_string s1("hello woooooooooooorld");
s1.show();
cout << "************************"<<endl;
My_string s2(500,'A');
s2.show();
cout << "************************"<<endl;
s2.push_back('B');
s2.show();
cout << "************************"<<endl;
s2.clear();
s2.show();
cout << "************************"<<endl;
s1.data();
s1.show();
cout << "************************"<<endl;
cout <<"s1.at(2) = "<<s1.at(2) <<endl;
return 0;
}
my_string.cpp
#include"My_string.h"
//判空
bool My_string::empty()
{
while(ptr[0]=='\0')
{
return 1;
}
return 0;
}
//尾插
void My_string::push_back(char value)
{
ptr[len]= value;
len++;
}
//at函数实现
char & My_string::at(int index)
{
return ptr[index-1];
}
//清空函数
void My_string::clear()
{
*ptr = '\0';
len=0;
}
//返回C风格字符串
char * My_string::data()
{
return ptr;
}
//返回实际长度
int My_string::get_length()
{
return this->len;
}
//返回当前最大容量
int My_string::get_size()
{
return this->size;
}
//二倍扩容
void My_string::Double_dilatation()
{
while(this->len>=this->size)
{
this->size *= 2;
}
char *p1 = new char (this->size);
*p1 = *(this->ptr);
p1 = this->ptr;
}
//显示数据函数
void My_string::show()
{
cout<< "ptr = " << ptr<<endl;
cout << "size = "<<size <<endl;
cout <<"len = "<< len <<endl;
}-
my_string.h
#ifndef MY_STRING_H
#define MY_STRING_H
#include <iostream>
using namespace std;
class My_string
{
private:
char *ptr; //指向字符数组的指针
int size=15; //字符串的最大容量
int len; //字符串当前容量
public:
//无参构造
My_string()
{
this->ptr = new char[size];
this->ptr[0] = '\0';
this->len = 0; //将当前容量设置为0
}
//有参构造
My_string(const char * src):ptr((char *)src)
{
int i=0,count = 0;
while(src[i])
{
count++;
i++;
}
this->len = count;
Double_dilatation();
}
My_string(int num,char value):len(num) //类似string(5,'A');
{
ptr = new char (this->size);
if(this->len>this->size)
{
Double_dilatation();
}
for(int i =0;i<num;i++)
{
ptr[i] = value;
}
}
//拷贝构造
My_string(const My_string & other):ptr(new char(*other.ptr)),size(other.size),len(other.len)
{
}
//拷贝赋值
My_string & operator=(const My_string & other)
{
if(this != & other)
{
*this->ptr = *other.ptr;
this->size = other.size;
this->len = other.len;
}
return *this;
}
//析构函数
~My_string()
{
delete ptr;
}
//判空
bool empty();
//尾插
void push_back(char value);
//at函数实现
char &at(int index);
//清空函数
void clear();
//返回C风格字符串
char * data();
//返回实际长度
int get_length();
//返回当前最大容量
int get_size();
//二倍扩容
void Double_dilatation();
//显示数据函数
void show();
};
#endif // MY_STRING_H