简体   繁体   中英

How can I friend a derived class function in the base class?

I have the following code:

#include <iostream>

class A {
    private:
        int a;
    public:
        void setA(int a_);
    friend int B::getA();
};

class B : public A {
    public:
        int getA();
};

void A::setA(int a_) {
    a = a_;
}

int B::getA() {
    return a;
}

int main() {
    B myB;
    myB.setA(9);

    std::cout << myB.getA()<< std::endl;
    return 0;
}

Compiling with g++ yields:

friend.cpp:10:16: error: use of undeclared identifier 'B'
    friend int B::getA();

My thinking is that when the compiler is going through the class A definition, it does not yet know about class B. Therefore, I can forward declare B to take care of this problem:

#include <iostream>

class B;

class A {
...

That doesn't quite work:

friend.cpp:10:16: error: incomplete type 'B' named in nested name specifier
    friend int B::getA();

It looks like the compiler isn't able to resolve the function as it is given.

How can I make a derived class function a friend in the base class?

Your code seems to violate the basic concept of data encapsulation. To resolve it, either make A::a protected, as @rici suggested, or define a getter in class A.

class A {
private:
   int a;
public:
   void setA(int a_);
   virtual int getA();
};

class B : public A {
public:
   int getA();
};

void A::setA(int a_) {
   a = a_;
}
int A::getA() {
   return a;
}

int B::getA() {
   return A::getA();
}

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