题目:
代码:
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
class my_string
{
private:
char *s;
public:
//构造函数
my_string(){}
my_string(char *str){
s=new char[strlen(str)];
strcpy(s,str);
}
//析构函数
~my_string(){
delete s;
}
//运算符重载函数
//+=运算符
my_string &operator+=(const my_string &R){
char *temp=new char(strlen(this->s));
strcpy(temp,this->s);
delete this->s;
this->s=new char[strlen(this->s)+strlen(R.s)];
strcpy(this->s,temp);
strcat(this->s,R.s);
delete temp;
return *this;
}
//+运算符
const my_string operator+(const my_string &R)const{
my_string temp;
temp.s=new char[strlen(this->s)+strlen(R.s)];
strcpy(temp.s,this->s);
strcat(temp.s,R.s);
return temp;
}
//>
bool operator>(my_string &R)const{
return strcmp(this->s,R.s)>0?true:false;
}
//<
bool operator<(my_string &R)const{
return strcmp(this->s,R.s)<0?true:false;
}
//==
bool operator==(my_string &R)const{
return !strcmp(this->s,R.s);
}
//[]
char &operator[](int index){
return this->s[index];
}
//成员函数
char *getStr(){
return s;
}
};
int main(int argc, const char *argv[])
{
my_string s1("hello");
cout<<s1.getStr()<<endl;
my_string s2=" world";
cout<<s2.getStr()<<endl;
s1+=s2;
cout<<s1.getStr()<<endl;
my_string s3;
s3=s1+s2;
cout<<s3.getStr()<<endl;
cout<<(s1>s2)<<endl;
cout<<(s1<s2)<<endl;
cout<<(s1==s2)<<endl;
cout<<s1[1]<<endl;
s1[4]='a';
cout<<s1[4]<<endl;
cout<<s1.getStr()<<endl;
return 0;
}
效果