1.思维导图
#include <iostream>
#include<cstring>
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){
this->str=new char[strlen(other.str)+1];
strcpy(str,other.str);
this->size=strlen(other.str);
}
//析构函数
~myString(){
}
void show(){
cout<<"str= "<<this->str<<endl;
cout<<"size="<<this->size<<endl;
}
//拷贝赋值函数
myString &operator=(const myString& other)
{
if(this!=&other)
{
this->str=other.str;
this->size=other.size;
}
return *this;
}
//判空函数
bool empty(){
if(0!=strlen(str))
{
cout<<"不为空"<<endl;
}else if(0==strlen(str))
{
return strlen(str);
}
}
//size函数
int str_size(){
return strlen(str);
}
//c_str函数
char *c_str(){
return str;
}
//at函数
char &at(int pos){
return str[pos];
}
//加号运算符重载
const myString operator+(const myString& R)const{
static myString temp;
temp.str=strcat(str,R.str);
temp.size=strlen(temp.str);
return temp;
}
//加等于运算符重载
myString & operator+=(const myString &R){
strcat(this->str,R.str);
this->size+=R.size;
return *this;
}
//关系运算符重载(>)
bool operator>(const myString & R)const
{
return this->str>R.str&&this->size>R.size;
}
};
int main()
{
//有参构造
myString s1("asd");
myString s2("fc");
s1.show();
s2.show();
//拷贝构造
myString s3(s1);
s3.show();
//判空函数
s1.empty();
s2.empty();
//size函数
s1.str_size();
s2.str_size();
s3.str_size();
//c_str函数
char c[20]="";
strcpy(c,s2.c_str());
cout<<"c="<<c<<endl;
//at函数
cout<<"s3="<<s3.at(3)<<endl;
//加号运算符重载
myString s4;
s4=s1+s2;
s4.show();
//加等于运算符重载
s1="111";
s2="22";
s1+=s2;
s1.show();
//关系运算符重载(>)
if(s3>s2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
return 0;
}