2个班级可以共享一个朋友功能吗? [英] Can 2 classes share a friend function?

查看:67
本文介绍了2个班级可以共享一个朋友功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我对朋友功能有疑问. 两个类可以具有相同的朋友功能吗? 说个例子 friend void f1(); 在A类和B类中声明.这可能吗?如果是这样,函数f1()可以访问两个类的成员吗?

Today i have a doubt regarding friend function. Can two classes have same friend function? Say example friend void f1(); declared in class A and class B. Is this possible? If so, can a function f1() can access the members of two classes?

推荐答案

一个示例将对此做出最好的解释:

An example will explain this best:

class B;                   //defined later

void add(A,B);

class A{
    private:
    int a;
    public:
    A(){ 
        a = 100;
    }
    friend void add(A,B);
};   

class B{
    private:
    int b;
    public:
    B(){ 
        b = 100;
    }
    friend void add(A,B);
};

void add (A Aobj, B Bobj){
    cout << (Aobj.a + Bobj.b);
}

main(){
    A A1;
    B B1;
    add(A1,B1);
    return 0;
}

希望这会有所帮助!

这篇关于2个班级可以共享一个朋友功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆