简体   繁体   中英

Making member function, friend of a class

I've been trying to write up a code to implement a member function that could access private data of a class by declaring it as a friend within the class. But my code is failing and I can't seem to figure out what's wrong with it:

#include <iostream>

using namespace std;

class A;
class B
{
    private:
    int b;       // This is to be accessed by member function of A

    public:
    friend void A::accessB();
};

class A
{
    private:
    int a;

    public:
    void accessB();
};

void A::accessB()
 {
     B y;
     y.b = 100;
     cout << "Done" << endl;
 }

int main(void)
{
    A x;
    x.accessB();
}

I am trying to access the private contents of B making use of getAccessB function which is member function of A. I have declared it as a friend. What's wrong with this?

A::accessB is not declared at the point of the friend declaration, so you can't refer to it. You can fix this by shifting the order of definitions and declarations such that A::accessB is visible to B :

class A
{
    private:
    int a;

    public:
    void accessB();
};

class B
{
    private:
    int b;

    public:
    friend void A::accessB();
};


void A::accessB()
 {
     B y;
     y.b = 100;
     cout << "Done" << endl;
 }

Note that making a function a friend just so that it can modify your private state is a bad code smell. Hopefully you are just doing this to understand the concepts.

The ordering. If you are referring to A::accessB , A must be declared by that point. Place the A class above the B , and it will work fine.

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