头文件
#ifndef SUANSHU_H
#define SUANSHU_H
#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):size(other.size)
{
str=new char[size+1];
strcpy(this->str,other.str);
cout<<"拷贝构造函数"<<endl;
}
//析构函数
~myString()
{
//释放指针空间
delete []str;
str = nullptr;
cout<<"析构函数:"<<this<<endl;
}
//拷贝赋值函数
myString & operator=(const myString &other) //拷贝的时候赋值,参数不变
{
if(this!=&other)
{
this->size=other.size;
//判断原来指针空间释放被清空
if(this->str!=NULL)
{
delete this->str;
}
str=new char[size+1];
strcpy(str,other.str);
}
cout<<"拷贝赋值函数:"<<endl;
return *this; //拷贝赋值需要返回自身引用(this是个指针)
}
void show()
{
cout<<"str="<<str<<" size="<<size<<endl;
}
//判空函数
bool myString_empty();
//size函数
int myString_size();
//c_str函数
char *myc_str();
//at函数
char &at(int pos);
//加号运算符重载
const myString operator+(const myString &R)const;
//加等于运算符重载
myString & operator+=(const myString &R);
//关系运算符重载(>)
bool operator>(const myString &R)const;
//中括号运算符重载
char & operator[](int index);
};
#endif // SUANSHU_H
源文件
#include "suanshu.h"
//判空函数
bool myString::myString_empty()
{
if(this->size==0)
{
return 1;
}
else
{
return 0;
}
}
//size函数
int myString::myString_size()
{
return this->size;
}
//c_str函数
char *myString::myc_str()
{
return str;
}
//at函数
char &myString::at(int pos)
{
return this->str[pos];
}
//加号运算符重载
const myString myString::operator+(const myString &R)const
{
myString S;
S.str=new char[this->size+R.size+1];
strcpy(S.str,this->str);
S.str=strcat(S.str,R.str);
return S.str;
}
//加等于运算符重载
myString & myString::operator+=(const myString &R)
{
strcat(this->str,R.str);
this->size=this->size+R.size;
return *this;
}
//关系运算符重载(>)
bool myString::operator>(const myString &R)const
{
if(strcmp(this->str,R.str)>=0)
return 1;
return 0;
}
//中括号运算符重载
char & myString::operator[](int index)
{
return this->str[index];
}
主函数
#include <iostream>
#include "suanshu.h"
using namespace std;
int main()
{
//定义并初始化两个字符串
myString s1("hello world");
myString s2("good");
//展示字符串和大小
s1.show();
s2.show();
//判断空,如果空返回1,否则返回0
cout<<s1.myString_empty()<<endl;
//字符串大小
cout<<"size="<<s2.myString_size()<<endl;
//求任意位置的字符
cout<<s1.at(4)<<endl;
//计算s1+s2
myString s3=s1+s2;
s3.show();
//s1+=s2 s1=s1+s2;
s1+=s2;
s1.show();
//比较s1和s2的大小
if(s3>s2)
{
cout<<"Yes"<<endl;
}
else
{
cout<<"NO"<<endl;
}
//求[]重载
s1[3]='H';
s1.show();
return 0;
}
2、思维导图