myString运算符重载
#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
char *str;//记录c风格的字符串
int size;//记录字符串的实际长度
public:
myString():size(10)
{
str=new char[size];
}
myString(const char *s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
}
//拷贝构造
myString(const myString & other)
{
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
}
//拷贝赋值
myString &operator= (const myString &other)
{
if(this == &other)
{
return *this;
}
delete []str;
size = other.size;
str = new char[size+1];
strcpy(str, other.str);
return *this;
}
//析构函数
~myString()
{
delete []str;
}
//判空函数
bool empty()
{
if(strlen(str) == 0)
{
return true;
}
else
{
return false;
}
}
//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];
}
//operator
char& operator[](const int pos)const
{
return str[pos];
}
const myString operator+(const myString& r)const
{
myString tmp;
tmp.size=size+r.size;
tmp.str=new char[tmp.size+1];
strcpy(tmp.str,str);
strcat(tmp.str,r.str);
return tmp;
}
bool operator==(const myString& r)const
{
return !strcmp(str,r.str);
}
bool operator!=(const myString& r)const
{
return strcmp(str,r.str);
}
bool operator<(const myString& r)const
{
return strcmp(str,r.str)<0;
}
bool operator>(const myString& r)const
{
return strcmp(str,r.str)>0;
}
bool operator<=(const myString& r)const
{
return strcmp(str,r.str)<=0;
}
bool operator>=(const myString& r)const
{
return strcmp(str,r.str)>=0;
}
myString& operator+=(const myString& r)
{
*this=*this+r;
return *this;
}
friend ostream& operator<<(ostream& l,myString& r);
friend istream& operator>>(istream& l,myString& r);
};
ostream& operator<<(ostream& l,myString& r)
{
cout<<r.str<<endl;
return l;
}
istream& operator>>(istream& l,myString& r)
{
char tmp[128];
cin>>tmp;
myString s(tmp);
r=tmp;
return l;
}
int main()
{
myString s1="1";
myString s11="1";
myString s2="2";
myString s3;
s3=s1+s2+s11;
cout<<s3;
s3+=s2;
cout<<s3;
cout<<boolalpha<<(s1==s11)<<(s1!=s11)<<endl;
cout<<(s2>=s11)<<(s2<=s11)<<endl;
cout<<s1[0];
return 0;
}