运算符重载
#include <iostream>
#include <cstring>
using namespace std;
class myString;
class myString
{
private:
char* str;
int size;
public:
myString():size(10)
{
str = new char(size);
strcpy(str,"");
cout<<"无参构造"<<endl;
}
myString(char* s)
{
size = strlen(s);
str = new char (size+1);
strcpy(str,s);
cout<<"有参构造"<<endl;
}
//析构函数
~myString()
{
delete []str;
cout<<"析构函数"<<endl;
};
const myString &operator=(const myString&n)
{
if (this != &n)
{
delete []this->str;
new char (n.size);
strcpy (this->str, n.str);
this->size = n.size;
}
return *this;
}
const myString operator+(const myString&m)const
{
myString temp;
temp.size = this->size+m.size;
temp.str = new char(temp.size+1);
memset(temp.str,0,temp.size+1);
strcat(temp.str,this->str);
strcat(temp.str,m.str);
cout<<"连接运算符"<<endl;
return temp;
}
const myString operator+=(const myString&m)
{
myString temp;
temp.size = this->size+m.size;
temp.str = new char(temp.size+1);
strcat(this->str,m.str);
strcat(temp.str,this->str);
cout<<"+=运算符"<<endl;
return temp;
}
char &operator[](size_t i)
{
if (i >= strlen(str))
{
cout<<"异常"<<endl;
}else
{
return str[i];
}
}
bool operator>(const myString&k)
{
if (strcmp(this->str,k.str) > 0)
{
cout<<this->str<<" "<<k.str<<endl;
return false;
}else
{
cout<<this->str<<" "<<k.str<<endl;
return true;
}
}
bool operator<(const myString&k)
{
if (strcmp(this->str,k.str) < 0)
{
cout<<this->str<<" "<<k.str<<endl;
return false;
}else
{
cout<<this->str<<" "<<k.str<<endl;
return true;
}
}
bool operator==(const myString&k)
{
if (strcmp(this->str,k.str) == 0)
{
cout<<this->str<<" "<<k.str<<endl;
return true;
}else
{
cout<<this->str<<" "<<k.str<<endl;
return false;
}
}
friend ostream &operator<<(ostream &L, const myString &K);
friend istream &operator>>(istream &L, myString &K);
void show(void)const
{
cout<<str<<endl;
}
};
ostream &operator<<(ostream &L, const myString &K)
{
L<<K.str<<endl;
return L;
}
istream &operator>>(istream &L, myString &K)
{
L>>K.str;
return L;
}
int main()
{
char s1[128] = ""; //s1 = 123
char s2[128] = ""; //s2 = 456
char s3[128] = "";
cout<<"请输入第一个字符串";
cin>>s1;
cout<<"请输入第一个字符串";
cin>>s2;
myString str1(s1);
myString str2(s2);
myString str3(s3);
myString str4(s3);
myString str5;
str1.show(); // 此时s1 = 123
str2.show(); // 此时s2 = 456
cout<<str1+str2<<endl; //s4 = 123465
str3 = str2; //s3 = 465
//str3 = str1; //s3 = 123465
str3.show();
if (str3 > str1)
{
cout<<"yes"<<endl;
}else
{
cout<<"no"<<endl;
}
if (str3 < str1)
{
cout<<"yes"<<endl;
}else
{
cout<<"no"<<endl;
}
if (str4 == str1)
{
cout<<"yes"<<endl;
}else
{
cout<<"no"<<endl;
}
str1[2] = 'M';
str1.show(); //此时str1的值为125456
cout<<"请输入str5>>>";
cin>>str5;
cout<<" str5 = "<<str5<<endl;
str5 += str5;
cout<<" str5 = "<<str5<<endl;
system("pause");
return 0;
}
思维导图