1.思维导图:
2.myString:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class myString
{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString():size(10)
{
str = new char[size]; //构造出一个长度为10的字符串
strcpy(str,""); //赋值为空串
}
//有参构造
myString(const char *s) //string s("hello world")
{
size = strlen(s);
str = new char[size+1];
strcpy(str, s);
}
myString(const myString &other):str(new char(*other.str)),size(other.size)//拷贝构造
{
cout<<"拷贝构造"<<endl;
strcpy(str, other.str);
}
~myString() //析构函数
{
delete str;
}
myString & operator=(const myString &other)//拷贝赋值函数
{
if(this!=&other)
{
this->size=other.size;
}
if(this->str!=NULL)
{
delete this->str;
}
this->str=new char(*other.str);
cout<<"拷贝赋值"<<endl;
strcpy(str, other.str);
return *this;
}
bool empty()const//判空函数
{
return !strlen(this->str);
}
int str_size()const
{
return strlen(this->str);
}
char *c_str() //c_str函数
{
return this->str;
}
char &at(int pos) //at函数
{
return *(this->str+pos-1);
}
//加号运算符重载
myString operator+(const myString &R)const
{
myString temp;
strcat(temp.str,this->str);
strcat(temp.str,R.str);
temp.size=this->size+R.size;
return temp;
}
//加等于运算符重载
myString &operator+=(const myString &R)
{
strcat(this->str,R.str);
this->size=R.size+this->size;
return *this;
}
//关系运算符重载(>)
bool operator>(const myString &R)const
{
if(strcmp(this->str,R.str)>0)
{
return true;
}
else
{
return false;
}
}
//中括号运算符重载
char &operator[](int pos)const
{
return *(this->str+pos-1);
}
void show()
{
cout<<"str="<<str<<" size="<<size<<endl;
}
};
int main()
{
myString s("yjh");
s.show();
myString s1=s;
s1.show();
myString s2;
s2=s;
s2.show();
myString s3;
if(s1.empty())
cout<<"s1为空"<<endl;
else
cout<<"s1非空"<<endl;
if(s3.empty())
cout<<"s3为空"<<endl;
else
cout<<"s3非空"<<endl;
cout<<"s1.str_size="<<s1.str_size()<<endl;
cout<<"s3.str_size="<<s3.str_size()<<endl;
cout<<"s1第一位为:"<<s1[1]<<" 第二位为:"<<s1[2]<<" 第三位为:"<<s1[3]<<endl;
s2=s+s1;
s2.show();
s1+=s;
s1.show();
if(s1>s2)
{
cout<<"s1>s2"<<endl;
}else
{
cout<<"s1<=s2"<<endl;
}
if(s1>s)
{
cout<<"s1>s"<<endl;
}else
{
cout<<"s1<=s"<<endl;
}
return 0;
}