#include <iostream>
#include <string.h>
using namespace std;
class mystring
{
private:
char *str;
int size;
public:
mystring():size(10)
{
str = new char[size];
strcpy(str,"");
}
//有参构造
mystring(const char *s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str,s);
cout<<"mystring::有参构造 "<<endl;
}
const mystring operator+(const mystring &s)const
{
mystring temp = this->str;
strcat(temp.str,s.str);
return temp;
}
mystring & operator=(const mystring &other)
{
if(this != &other)
{
strcpy(this->str,other.str);
this->size = other.size;
}
return *this;
}
bool operator==(const mystring &s) const
{
return (strcmp(this->str,s.str) == 0);
}
bool operator!=(const mystring &s) const
{
return (strcmp(this->str,s.str) == -1);
}
bool operator>(const mystring &s) const
{
return (strcmp(this->str,s.str) == 1);
}
bool operator<(const mystring &s) const
{
return (strcmp(this->str,s.str) == -1);
}
bool operator>=(const mystring &s) const
{
return (strcmp(this->str,s.str) == 1);
}
bool operator<=(const mystring &s) const
{
return (strcmp(this->str,s.str) == -1);
}
friend ostream &operator<<(ostream &L,const mystring &s);
friend istream &operator>>(istream &L,const mystring &s);
void show()
{
cout<<"str = "<<str<<endl;
}
};
ostream &operator<<(ostream &L,const mystring &s)
{
L<<s.str<<endl;
return L;
}
istream &operator>>(istream &L,const mystring &s)
{
L>>s.str;
return L;
}
int main()
{
mystring m1("hello");
m1.show();
mystring m2("world");
m2.show();
mystring m3;
m3 = m1;
m3.show();
mystring m4;
m4 = m1 + m2;
m4.show();
if(m1 == m2)
{
cout<<"相等"<<endl;
}
else
{
cout<<"不相等"<<endl;
}
if(m1 != m2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(m1 > m2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(m1 < m2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(m1 >= m2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
if(m1 <= m2)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
cout<<"m1 = "<<m1<<endl;
cout<<"请输入m2:"<<endl;
cin>>m2;
cout<<"m2 = "<<m2<<endl;
return 0;
}
在mystring的基础上,将能够重载的运算符全部重载
最新推荐文章于 2024-07-17 20:43:45 发布