要求:
算术运算符:+
赋值运算符:+=
下标运算符:[]
关系运算符:>、<、==、!=、>=、<=
插入提取运算符:<<、>>
要求:注意数据的保护(const)
代码如下:
#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char *data;
int len;
public:
//无参构造默认长度为15
My_string():len(15)
{
data = new char[len];
data[0] = '\0';
}
//有参构造
My_string(const char *str)
{
len = strlen(str);
data = new char[len+1];
strcpy(data,str);
}
My_string(int n, char ch)
{
len = n;
data = new char[n+1];
for(int i = 0; i < n; i++)
data[i] = ch;
}
//析构函数
~My_string()
{
delete []data;
//cout<<"析构函数"<<" this = "<<this<<endl;
}
//拷贝构造函数
My_string(const My_string &str ):data(str.data)
{
data = new char[str.len+1];
strcpy(data,str.data);
}
//拷贝赋值函数
My_string & operator=(const My_string &str)
{
if(this!=&str){
data=new char[str.len+1];
strcpy(data,str.data);
len=str.len;
}
return *this;
}
//算术运算符
const My_string operator+(const My_string &str)const
{
My_string temp; //定义临时类对象
temp.len = this->len + str.len;
temp.data = new char[temp.len+1];
strcpy(temp.data,this->data);
strcat(temp.data,str.data);
return temp;
}
//赋值运算符
My_string &operator+=(const My_string &str)
{
this->len += str.len;
strcat(this->data,str.data);
return *this;
}
//下标运算符:[]
char operator[](int n) const
{
return data[n];
}
//关系运算符>
bool operator>(const My_string &str) const
{
return strcmp(this->data,str.data)>0?1:0;
}
//关系运算符==
bool operator==(const My_string &str) const
{
return strcmp(this->data,str.data)==0?1:0;
}
//关系运算符<=
bool operator<=(const My_string &str) const
{
return strcmp(this->data,str.data)<=0?1:0;
}
//c_str函数
char *c_str()
{
return data;
}
//len函数
int size()
{
return len;
}
//empty函数
bool empty() //判断是否为空
{
if(len==0)
{
return 0;
}
else
{
return 1;
}
}
//at函数
char at(int n)
{
return *(data+n);
}
void show()
{
cout<<data<<endl;
}
friend ostream &operator<<(ostream &L,const My_string &str);
friend istream &operator>>(istream &L,const My_string &str);
};
//插入运算符
ostream &operator<<(ostream &L,const My_string &str)
{
L<<str.data;
return L;
}
//提取运算符
istream &operator>>(istream &L,const My_string &str)
{
L>>str.data;
return L;
}
int main()
{
My_string s("hello world");
s.show();
My_string s2(5,'b');
s2.show();
My_string s3 = s2;
s3.show();
My_string s4;
s4 = s;
s4.show();
cout<<"s4长度为"<<s4.size()<<endl;
if(s4.empty())
{
cout<<"s4不空"<<endl;
}
else
{
cout<<"s4空"<<endl;
}
cout<<"s4[1] = "<<s4.at(1)<<endl;
cout<<"****************************************************"<<endl;
My_string r1;
r1 = s +s2;
r1.show();
r1 += s;
r1.show();
s.show();
cout<<"r1的第二个元素是"<<r1[1]<<endl;
if(r1>s)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(r1==s)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(r1<=s)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
cout<<r1<<endl;
cin>>s;
cout<<s;
return 0;
}
结果如图所示:
![](https://img-blog.csdnimg.cn/img_convert/f80a56989542fc7836edd460de1b55e8.png)