|
|
发表于 2012-7-18 08:39:14
|
显示全部楼层
- #include<iostream>
- using namespace std;
- //由于VC6不标准,使用友元必须加上以下3行
- class String;
- bool operator>(String &string1, String &string2);
- bool operator==(String &string1, String &string2);
- bool operator<(String &string1, String &string2);
- //由于VC6不标准,使用友元必须加上以上3行
- class String
- {
- public:
- String();
- 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;
- };
- void compare(String &string1, String &string2);
- int main()
- {
- String s1("libin");
- String s2("chengbaoshu");
- String s3("abit");
- String s4("libin");
- compare(s1,s2);
- compare(s4,s3);
- compare(s1,s4);
- cout<<endl;
- return 0;
- }
- String::String()
- {
- p=NULL;
- }
- String::String(char *str):p(str){}
- bool operator>(String &string1, String &string2) //下面定义的三个 运算符重载函数都是出同一个错误
- {
- if(strcmp(string1.p,string2.p)>0) //就是我定义的是 友元函数 但是为什么不能访问String类的 私有成员p?
- 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 String::display()
- {
- cout<<p;
- }
- void compare(String &string1, String &string2)
- {
- if(operator>(string1,string2)==1) //">"为什么这里说 我 含糊的 调用 函数
- {
- string1.display();
- cout<<">";
- string2.display();
- cout<<endl;
- }
- else
- {
- if(operator==(string1,string2)==1)
- {
- string1.display();
- cout<<"==";
- string2.display();
- cout<<endl;
- }
- else
- {
- if(operator<(string1,string2)==1)
- {
- string1.display();
- cout<<"<";
- string2.display();
- cout<<endl;
- }
- }
- }
- }
复制代码 |
|