#include <iostream>
#include <cstring>
using namespace std;
class String
{
public:
String()
{
p=NULL;
}
String( char *str);
friend bool operator >(String &string1,String &string2);
friend bool operator <(String &string1,String &string2);
friend bool operator ==(String &string1,String &string2);
void display();
private:
char *p;
};
String::String( char *str)
{
p=str;
}
void String::display()
{
cout<<p;//输出p所指向的字符串
}
bool operator>(String &string1,String &string2)
{
if(strcmp(string1.p,string2.p)>0)
{
return true;
}
else
return false;
}
bool operator<(String &string1,String &string2)
{
if(strcmp(string1.p,string2.p)<0)
{
return true;
}
else
return false;
}
bool operator==(String &string1,String &string2)
{
if(strcmp(string1.p,string2.p)==0)
{
return true;
}
else
return false;
}
void compare(String &string1,String &string2)
{
if(operator >(string1,string2)==1)
{
string1.display();cout<<">";string2.display();
}
else if(operator <(string1,string2)==1)
{
string1.display();cout<<"<";string2.display();
}
else if(operator ==(string1,string2)==1)
{
string1.display();cout<<"==";string2.display();
}
cout<<endl;
}
int main()
{
String string1("Hello"),string2("Book"),string3("computer"),string4("Hello");
compare(string1,string2);
compare(string2,string3);
compare(string1,string4);
return 0;
}
ubuntu@ubuntu:~$ g++ 13.cpp -o a
13.cpp: In function ‘int main()’:
13.cpp:79:24: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
String string1("Hello"),string2("Book"),string3("computer"),string4("Hello");
^
13.cpp:79:40: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
String string1("Hello"),string2("Book"),string3("computer"),string4("Hello");
^
13.cpp:79:60: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
String string1("Hello"),string2("Book"),string3("computer"),string4("Hello");
^
13.cpp:79:77: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
String string1("Hello"),string2("Book"),string3("computer"),string4("Hello");
^
ubuntu@ubuntu:~$ ./a
Hello>Book
Book<computer
Hello==Hello
要注意这个程序中,需用到头文件#include <cstring>,有关这个头文件的使用,目前我也不是太清楚!对于运行的警告信息,暂时无法作出解释!