运算符重载字符串类
/*
设计一个mystring类,包括数据成员char * pstr;
和int length; 通过运算符重载实现字符串的输入
>>、输出<<、连接+=、赋值=、关系运算(==、!=、
>、<)、下标[]等运算。
*/
#include <iostream>
#include <cstring>
#include<stdlib.h>
using namespace std;
class mystring
{
public:
mystring(string s);
//mystring(char *p);
~mystring()
{
}
mystring& operator=(mystring& s);
void operator+=(mystring & a)
{
this->pstr = (char*)realloc(this->pstr, this->length + a.length + 1); strcpy(this->pstr + (this->length), a.pstr);
}
char & operator [](int n);
bool operator ==(const mystring & s)
{
if (strcmp(this->pstr, s.pstr) == 0)
return 1;
else
return 0;
}
bool operator !=(const mystring & s)
{
if (strcmp(this->pstr, s.pstr) != 0)
return 1;
else
return 0;
}
bool operator <(const mystring & s)
{
if (strcmp(this->pstr, s.pstr)<0)
return 1;
else
return 0;
}
bool operator >(const mystring & s)
{
if (strcmp(this->pstr, s.pstr)>0)
return 1;
else
return 0;
}
friend ostream & operator <<(ostream & os, const mystring & s)
{
return os << s.pstr<< strlen(s.pstr);
}
friend istream & operator >>(istream & is, mystring & s)
{
/* delete []s.pstr;
is >>s.length ;
s.pstr = new char[s.length + 1];
is >> s.pstr;
*(s.pstr + s.length) = '\0';
*/
is>>s.pstr;
return is;
}
private:
char *pstr;
int length;
};
mystring::mystring(string s)
{
char *p=&s[0];
this->pstr = (char *)malloc(strlen(p) + 1);
strcpy(this->pstr, p);
this->length = strlen(p);
}
//有警告
/*
mystring::mystring(char *p)
{
this->pstr = (char *)malloc(strlen(p) + 1);
strcpy(this->pstr, p);
this->length = strlen(p);
}
*/
mystring& mystring:: operator =(mystring & s)
{
delete[]pstr; this->pstr = new char[strlen(s.pstr) + 1];
if (pstr)strcpy(this->pstr, s.pstr);
return *this;
}
char& mystring::operator[](int n)
{
static char ch = 0;
if (n > length || n < 0)
return ch;
return *(pstr + n);
}
int main()
{
mystring a("abc"), b("efg");
//cin>>a>>b;
cout << a << " " << b << endl;
a = b;
cout << a << endl;
a += b;
cout << a << endl;
cin >> a;
cout << a << endl;
if (a > b)
cout << "a字符串更大:" << a << endl;
else if (a < b)
cout << "b字符串更大:" << b << endl;
else
cout << "a,b相等 " << a << endl;
if (a != b)
cout << "a,b不相等 " << endl;
a[1] = 'g';
cout << a << endl;
return 0;
}