Can 2 classes share a friend function?

后端 未结 4 756
轻奢々
轻奢々 2021-01-12 12:05

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 t

相关标签:
4条回答
  • 2021-01-12 12:46

    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;
    }
    
    0 讨论(0)
  • 2021-01-12 12:57

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

    0 讨论(0)
  • 2021-01-12 12:58
    #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);
    }
    
    0 讨论(0)
  • 2021-01-12 12:59

    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!

    0 讨论(0)
提交回复
热议问题