1.实现mystring类
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
class MyString
{
private:
//字符串
char *str=nullptr;
//最大长度
int size=15;
//元素个数
int len=0;
public:
//无参构造
MyString()
{
str=new char[size];
strcpy(str,"");
}
//有参构造
MyString(const char *s)
{
this->len=strlen(s);
if(this->len>this->size)
{
this->size=15*pow(2,(this->len)/15);
}
else if(this->len==15)
{
this->size=30;
}
str=new char[this->size];
strcpy(this->str,s);
}
//拷贝构造
MyString(const MyString &other):
size(other.size),
len(other.len)
{
this->str=new char[other.size];
strcpy(this->str,other.str);
}
//析构函数
~MyString()
{
delete []str;
this->str=nullptr;
}
//拷贝赋值函数
MyString &operator=(const MyString &other)
{
//防止自己给自己赋值
if(this!=&other)
{
this->len=other.len;
this->size=other.size;
this->str=new char[other.size];
strcpy(this->str,other.str);
}
return *this;
}
//判空函数
bool empty()
{
if(this->len==0)
return true;
return false;
}
//length函数
int length()
{
if(this->str==nullptr||empty())
return 0;
return this->len;
}
//c_str函数
char *c_str()
{
//返回字符串
return this->str;
}
//at函数
char &at(int i)
{
//越界检查
if(i<0||i>this->len-1)
{
cout<<"越界访问!"<<endl;
return this->str[len];
}
return this->str[i];
}
//最大容量
int capacity()
{
return this->size;
}
//加号运算符重载
const MyString operator+(const MyString &other)const
{
int len=this->len+other.len;
char str1[len+1];
strcpy(str1,this->str);
MyString s1(strcat(str1,other.str));
return s1;
}
//加等于号重载
MyString& operator+=(const MyString &other)
{
this->len+=other.len;
if(this->len>this->size)
{
this->size*=pow(2,(this->len+other.len-1)/15);
}
else if(this->len==15)
this->size=30;
char str1[this->size];
strcpy(str1,this->str);
delete []this->str;
this->str=new char[this->size];
strcat(str1,other.str);
strcpy(this->str,str1);
return *this;
}
//关系运算符重载(>)
bool operator>(const MyString &other)
{
if(strcmp(this->str,other.str)>0)
return true;
return false;
}
};
int main()
{
MyString s1("hellohellohellohellohellohello");
MyString s2("world");
MyString s3;
s3=s1;
MyString s4(s2);
cout<<"最大容量"<<s1.capacity()<<endl;
cout<<s3.at(0)<<endl;
cout<<s1.c_str()<<endl;
cout<<s3.length()<<endl;
if(s1.empty())
cout<<"字符串为空"<<endl;
else {
cout<<"字符串不为空"<<endl;
}
if(s1>s2)
{
cout<<"s1>s2"<<endl;
}
else
{
cout<<"s1<s2"<<endl;
}
s3=s1+s2;
cout<<s3.at(7)<<endl;
cout<<"最大容量"<<s3.capacity()<<endl;
s3=s1;
cout<<s3.length()<<endl;
s4+=s2;
cout<<s4.at(7)<<endl;
return 0;
}
2.脑图