基于昨天写的Int运算符的重载,今天又完善了一下Stringl类的运算符重载。代码如下:
#include<iostream>
using namespace std;
class String;
ostream& operator<<(ostream &out,const String &s);
class String
{
friend ostream& operator<<(ostream &out,const String &s);
public:
String(const char *str) //普通构造函数
{
m_data = new char[strlen(str)+1];
strcpy(m_data,str);
}
String(const String &s) //拷贝构造函数
{
m_data = new char[strlen(s.m_data) +1];
strcpy(m_data,s.m_data);
}
~String()
{
delete []m_data;
}
String& operator=(const String &s)
{
if ( this != &s)
{
delete[]m_data;
m_data = new char[strlen(s.m_data) +1];
strcpy(m_data,s.m_data);
}
return *this;
}
public:
String operator+(const String &s)
{
char *p = new char[strlen(m_data) +strlen(s.m_data)+1];
strcpy(p,m_data);
strcat(p,s.m_data);
String tmp(p);
delete []p;
return tmp;
}
//////////////////////////////////////////////////
bool operator==(const String &s)
{
if (strcmp(m_data,s.m_data) == 0)
return true;
else
return false;
}
bool operator!=(const String &s)
{
if (strcmp(m_data,s.m_data) != 0)
return true;
else
return false;
}
bool operator>(const String &s)
{
if (strcmp(m_data,s.m_data) > 0)
return true;
else
return false;
}
bool operator<(const String &s)
{
if (strcmp(m_data,s.m_data) < 0)
return true;
else
return false;
}
///////////////////////////////////////
private:
char *m_data;
};
ostream& operator<<(ostream &out,const String &s)
{
out<<s.m_data;
return out;
}
void main()
{
String s1("hello");
String s2("world");
String s3= s1 + s2;
cout<<s1<<endl;
cout<<s3<<endl;
String s4("hello,world");
String s5("hello,world");
String s6("hello");
if (s4 == s5)
{
cout<<"s4和s5相等!"<<endl;
}
else
{
cout<<"s4和s5不相等!"<<endl;
}
if(s4 > s6)
{
cout<<"s4大于s6!"<<endl;
}
else if(s4 < s6)
{
cout<<"s4小于s6!"<<endl;
}
else
{
cout<<"s4等于s6"<<endl;
}
}