设计一个字符串类MyString, 要求该字符串类MyString实现如下运算符重载和操作

来源:百度知道 编辑:UC知道 时间:2024/06/24 12:11:01
设计一个字符串类MyString, 要求该字符串类MyString实现如下运算符重载和操作
1. 关系运算符: 等于(==), 不等于(!=), 小于(<), 大于(>);
2. 算术运算符: 加(+);
3. 赋值运算: =;
4. 下标运算符: [];
要求定义主函数,实现对你定义的字符串类MyString的正确性测试

提示:
1. 假如定义两个字符串类对象s1和s2,且对它们赋值s1为abc,s2为def,那么s1+s2即为abcdef
2. 假如定义一个字符串类对象s1,且对其赋值为abcd,那么 s1[0]为取字符串对象中的第一个字符,即字符a

#include <iostream>
#include <string>
using namespace std;

class my
{
public:
my(){}
my(const char * s){str=s;}
my(const my & s){str=s.str;}
my(const string & s){str=s;}
my operator =(const my & s){this->str=s.str;return * this;}
char operator [](int index) const{return str[index];}
bool operator ==(const my & s){return s.str==str;}
bool operator !=(const my & s){return s.str!=str;}
bool operator <(const my & s){return str<s.str;}
bool operator >(const my & s){return str>s.str;}
friend my operator +(const my & a,const my & b){return my(a.str+b.str);}
friend ostream & operator <<(ostream & os,my & s){return os<<s.str;}
private:
string str;
};

int main()
{
my a="abc",b;
b="def";
cout<<a+b<<endl;
cout<<a[2]<<endl;
my c;
c=a+b;
cou