#include<iostream.h>//ÖØÔØÔËËã·û"=="£¬"<",">"
class String_a{
public:
String_a(){
p = NULL;

}
String_a(char * str){
this->p =  str;
}
friend bool operator >(String_a &string1,String_a &string2);
friend bool operator <(String_a &string1,String_a &string2);
friend bool operator ==(String_a &string1,String_a &string2);
friend void compare(String_a &string1,String_a &string2);

void display();
private:
char *p;
}; bool operator >(String_a &string1,String_a &string2){
int a = 0;
int b = 0;
while(*string1.p){
a++;
string1.p++;
}
while(*string2.p){
b++;
string2.p++;
}
if(a>b){
return true;
}else{
return false;
}
}
bool operator <(String_a &string1,String_a &string2){
int a = 0;
int b = 0;
/*cout<<*(string1.p);
cout<<endl;
cout<<string1.p;
cout<<endl;*/
while(*(string1.p)){
a++;
string1.p++;
}
while(*string2.p){
b++;
string2.p++;
}
if(a<b){
return true;
}else{
return false;
}}
bool operator ==(String_a &string1,String_a &string2){
int a = 0;
int b = 0;
while(*string1.p){
a++;
string1.p++;
}
while(*string2.p){
b++;
string2.p++;
}

if(a==b){
return true;
}else{
return false;
}}

void String_a::display(){
cout<<p;

}
void compare(String_a &string1,String_a &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();
}
}
int main(){
String_a string1("hello"),string2("book"),string3("Computer"),string4("hello");
//cout<<(string1>string2)<<endl;
//string1.display();
//cout<<(string1<string2)<<endl;
//cout<<(string1==string2)<<endl;
compare(string1,string2);
cout<<endl;
compare(string2,string3);
cout<<endl;
//compare(string1,string4);

  return 0;
}
运行结果如下:
   >
   ==
我想输出的结果如下:
hello>book
book<Computer但是为什么compare中调用的display()函数没有输出p所指的字符串,我自己也调试的许久,请高人指点,

解决方案 »

  1.   

    比较函数字符串处理有问题,改为
    bool operator >(String_a &string1,String_a &string2){
    int a = 0;
    int b = 0;
    char *p = string1.p; while(*p){
    a++;
    p++;
    }
    p = string2.p;
    while(*p){
    b++;
    p++;

    if(a>b){
    return true;
    }else{
    return false;
    }
    }
    bool operator <(String_a &string1,String_a &string2){
    int a = 0;
    int b = 0;
    /*cout<<*(string1.p);
    cout<<endl;
    cout<<string1.p;
    cout<<endl;*/
    char *p = string1.p; while(*p){
    a++;
    p++;
    }
    p = string2.p;
    while(*p){
    b++;
    p++;
    }
    if(a<b){
    return true;
    }else{
    return false;
    }



    }
    bool operator ==(String_a &string1,String_a &string2){
    int a = 0;
    int b = 0;
    char *p =  string1.p; while(*p){
    a++;
    p++;
    }
    p = string2.p;
    while(*p){
    b++;
        p++;
    }

    if(a==b){
    return true;
    }else{
    return false;
    }

    }
    具体的原因你能分析出来吗
      

  2.   

    你的*p应该指向String的首地址,才会输出字符串的。