鱼C论坛

 找回密码
 立即注册
查看: 3877|回复: 2

C++中关于友元运算符重载函数访问权限的问题

 关闭 [复制链接]
发表于 2011-6-13 11:00:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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的吗?


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2011-6-13 12:08:49 | 显示全部楼层
public,private,protected对友元函数没有作用(否则你认为一个被private修饰的友元函数存在的价值是什么?),友元函数在类中任何位置都可以写。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
 楼主| 发表于 2011-6-13 12:12:16 | 显示全部楼层

谢谢啊{:3_59:}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-2-7 08:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表