作业需求:
在My_string类的基础上,完成运算符重载
算术运算符:+
赋值运算符:+=
下标运算符:[]
关系运算符:>、<、==、!=、>=、<=
插入提取运算符:<<、>>
要求:注意数据的保护(const)
实现过程:
#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *date;
int size;
public:
my_string():size(15)
{
date = new char [size];
date[0]='\0';
cout<<"无参构造完成"<<endl;
}
my_string(const char *str)
{
size=sizeof (str);
date = new char[size];
strcpy(date,str);
cout<<"有参构造完成"<<endl;
}
my_string(int n, char ch)
{
size=n*sizeof(ch);
date = new char[size];
for(int i=0;i<n;i++)
{
date[i]=ch;
}
cout<<"多参构造完成"<<endl;
}
~my_string()
{
delete date;
cout<<"析构函数完成"<<endl;
}
my_string(const my_string &s)
{
this->size=s.size;
this->date=new char[this->size];
strcpy(this->date,s.date);
cout<<"拷贝构造函数"<<endl;
}
my_string & operator=(const my_string &s)
{
this->size=s.size;
this->date=new char[this->size];
strcpy(this->date,s.date);
cout <<"拷贝赋值函数"<<endl;
return *this;
}
const char *c_str()
{
return date;
}
int my_size()
{
return size;
}
bool empty()
{
return strlen(date);
}
char &at(int n)
{
if(n<0 ||n >size-1)
{
cout<<"数值越界"<<endl;
}
return date[n];
}
void show()
{
cout<<"date = "<<date<<endl;
}
const my_string operator+( const my_string &R)
{
my_string temp;
strcpy(temp.date,this->date);
strcat(temp.date,R.date);
return temp;
}
const my_string operator+=(const my_string &R)
{
strcat(this->date,R.date);
return *this;
}
char &operator[](int n)const
{
if(n<0 ||n >size-1)
{
cout<<"数值越界"<<endl;
}
return date[n];
}
bool operator>(my_string &R)
{
return strcmp(this->date,R.date)>0;
}
bool operator<(my_string &R)
{
return strcmp(this->date,R.date)<0;
}
bool operator==(my_string &R)
{
return strcmp(this->date,R.date)==0;
}
bool operator!=(my_string &R)
{
return strcmp(this->date,R.date)!=0;
}
bool operator>=(my_string &R)
{
return strcmp(this->date,R.date)>=0;
}
bool operator<=(my_string &R)
{
return strcmp(this->date,R.date)<=0;
}
friend ostream &operator<<(ostream &L, const my_string &R);
friend istream &operator>>(istream &L, const my_string &R);
};
ostream &operator<<(ostream &L, const my_string &R)
{
L<<R.date;
return L;
}
istream &operator>>(istream &L, const my_string &R)
{
L>>R.date;
return L;
}
int main()
{
my_string s1("hello ");
my_string s2("world");
s1=s1+s2;
s1.show();
s1+=s2;
s1+=s2;
s1.show();
s1[0]='H';
cout<<s1[4]<<endl;
s1.show();
if(s1>s2)
{
cout<<"s1>s2"<<endl;
}
if (s2>s1)
{
cout <<"s2>s1"<<endl;
}
if(s1<s2)
{
cout<<"s1<s2"<<endl;
}
if (s2<s1)
{
cout <<"s2<s1"<<endl;
}
if(s1==s1)
{
cout <<"s1==s1"<<endl;
}
if(s1!=s1)
{
cout <<"s1!=s1"<<endl;
}
if(s1!=s2)
{
cout <<"s1!=s2"<<endl;
}
if(s1>=s2)
{
cout <<"s1>=s2"<<endl;
}
if(s1<=s2)
{
cout <<"s1<=s2"<<endl;
}
cout<<s1<<endl;
my_string s3;
cin>>s3;
s3.show();
return 0;
}
实验结果: