|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
#include <string.h>
using namespace std;
class String
{
// friend bool operator>(String &str1, String &str2);
// friend bool operator<(String &str1, String &str2);
// friend bool operator==(String &str1, String &str2);
public:
String(void){p = NULL;}
String(char * str):p(str){}
void display(void){cout << p;}
friend bool operator>(String &str1, String &str2);
friend bool operator<(String &str1, String &str2);
friend bool operator==(String &str1, String &str2);
private:
char *p;
};
bool operator>(String &str1, String &str2)
{
if (strcmp(str1.p, str2.p) > 0)
{
return true;
}
return false;
}
bool operator<(String &str1, String &str2)
{
if (strcmp(str1.p, str2.p) < 0)
{
return true;
}
return false;
}
bool operator==(String &str1, String &str2)
{
if (strcmp(str1.p, str2.p) == 0)
{
return true;
}
return false;
}
void compare(String &str1, String &str2)
{
if (operator>(str1, str2))
{
str1.display();
cout << " > ";
str2.display();
cout << endl;
}
else if (operator<(str1, str2))
{
str1.display();
cout << " < ";
str2.display();
cout << endl;
}
else if (operator==(str1, str2))
{
str1.display();
cout << " == ";
str2.display();
cout << endl;
}
}
int main(void)
{
String str1("hello"), str2("book"), str3("computer"), str4("book");
compare(str1, str2);
compare(str1, str3);
compare(str2, str4);
return 0;
}
程序编译通过,第一个类中三个友元运算符重载函数如果换成注释中的这种写法,即把它们放在public之前,使用默认的访问权限,也编译运行通过,为什么呢?默认的访问权限不是private的吗?
|
|