在myString的基础上,将能重载的运算符全部进行重载
#include <iostream>
#include<cstring>
using namespace std;
class myString
{
private:
char *str; //记录c风格的字符串
int size;
public:
//无参构造
myString():size(10)
{
str=new char[size];
strcpy(str,"");
}
//有参构造
myString(const char *s)
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
}
//拷贝构造--深拷贝
myString(myString &other):size(other.size),str(new char[other.size+1])
{
strcpy(str,other.str);
cout<<"myString::拷贝构造"<<endl;
}
//析构函数
~myString()
{
delete []str;
// cout<<"myString::析构函数"<<endl;
}
//判空函数
bool empty()
{
if(strlen(str)==0)
return false;
else
return true;
}
//size函数
int length()
{
return size;
}
//c_str函数
const char *c_str()
{
return str;
}
//at函数
char &at(int pos)
{
if(pos>=size||pos<0)
{
cout<<"错误-访问越界"<<endl;
}
return str[pos];
}
//成员函数=赋值运算符重载
myString &operator=(const myString &R)
{
this->str=R.str;
return *this;
}
//成员函数重载[]运算符
char &operator[](const int &index)const
{
if(index<0||index>=size)
{
cout<<"错误-访问越界"<<endl;
}
return this->str[index];
}
//成员函数重载+号运算符
const myString operator+(const myString &other)const
{
myString temp;
temp.size = this->size + other.size;
temp.str = new char[size+1];
*temp.str = '\0';
strcat(temp.str,this->str);
strcat(temp.str,other.str);
return temp;
}
//成员函数重载==运算符
bool operator==(const myString &other)const
{
if(strcmp(this->str,other.str)==0)
return true;
else
return false;
}
//成员函数重载>运算符
bool operator>(const myString &other)const
{
if(strcmp(this->str,other.str)>0)
return true;
else
return false;
}
//成员函数重载<运算符
bool operator<(const myString &other)const
{
if(strcmp(this->str,other.str)<0)
return true;
else
return false;
}
friend ostream &operator<<(ostream &L,myString &other);
friend istream &operator>>(istream &L,myString &other);
};
//全局函数版实现<<运算符重载:输出所有内容
ostream &operator<<(ostream &L,myString &other)
{
L<<other.c_str()<<endl;
return L;
}
//全局函数版实现>>运算符重载
istream &operator>>(istream &L,myString &other)
{
char s[other.length()];
cin>>s;
strcpy(other.str,s);
return L;
}
int main()
{
//有参构造
myString s1("helloya");
cout<<"s1="<<s1.c_str()<<endl;
//拷贝构造
myString s2(s1);
cout<<"s2="<<s2.c_str()<<endl;
//成员函数实现=号运算重载
myString s3;
s3=s2;
cout<<"\"=\":s3= "<<s3.c_str()<<endl;
//成员函数实现[]重载
cout<<"s3[4]= "<<s3[4]<<endl;
//成员函数实现字符串+重载
myString s5;
s5=s1+s2;
cout<<"\"+\":s5= "<<s5.c_str()<<endl;
//成员函数实现重载==运算符
cout<<"\"==\":(s1==s2):";
if(s1==s2)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
//成员函数实现重载>运算符
cout<<"\">\":(s5>s2):";
if(s5>s2)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
//成员函数实现重载<运算符
cout<<"\"<\":(s5<s2):";
if(s5<s2)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
/*
cout<<"s2.length="<<s2.length()<<endl;
cout<<"s2.c_str="<<s2.c_str()<<endl;
cout<<"s2.at(5)="<<s2.at(5)<<endl;*/
return 0;
}
运行结果: