简体   繁体   中英

Class Member Functions and Classes as Friends

I've written two classes: the function of the first class cannot access to the private member of the second class even though that function is a friend to second class. then I found this example from msdn.microsoft.com but there is still an error: cannot access private member declared in class B

here is code from MSDN :

class B;
class A {
public:
    int Func1(B& b);

private:
    int Func2(B& b);
};

class B {
private:
    int _b;

    // A::Func1 is a friend function to class B
    // so A::Func1 has access to all members of B
    friend int A::Func1(B&);
};

int A::Func1(B& b) { return b._b; }//the same error as the one below is here
int A::Func2(B& b) { return b._b; }  

when I write class A itself as friend for B there is no error but I want to have only the function that I want to be a friend for class B not whole class A

Is it my compiler fault or this code is wrong?

i just added a declaration for the class B (called forward declaration of a class ) at the top and it compiles. You need to declare the class B before you use it as a parameter in your member functions of class A .

Here is the code ->

#include<iostream>

class B;

class A {
public:
    int Func1(B& b);

private:
    int Func2(B& b);
};

class B {
private:
    int _b;


    // A::Func1 is a friend function to class B
    // so A::Func1 has access to all members of B
    friend int A::Func1(B&);
};

int A::Func1(B& b) { return b._b; }//the same error as the one below    is here
//int A::Func2(B& b) { return b._b; } 

int main(void){ return 0; }

If the error still persists then maybe your compiler is at fault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM