Can 2 classes share a friend function?

社会主义新天地 提交于 2019-12-01 16:36:17

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;
}

Hope this helps!

There is no restriction on what function can or cannot be friends's of class's, so yes there's no problem with this.

SDL_Developer

correction to the above code

#include<iostream>
using namespace std;
class B;                   //defined later
class A;                  //correction (A also need be specified)
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;
}
user7970196
#include<iostream>

using namespace std;

class first
{
    friend void getdata(first object1, int i);
};

class second
{
    friend void getdata(second object2, int j);
};

getdata(first object1, int i, second object2, int j)
{
    cout<<i+j;
}

main()
{
    first object1;
    second object2;
    getdata(object1, 5, object2, 7);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!