C++成员函数做友元 报无法访问私有成员如果是friend class B,如何解决?

C++成员函数做友元 报无法访问私有成员
如果是friend class B; 就可以访问所以应该不是代码写错了 但是我搜了一下成员函数做友元是我下图的语法啊 不明白为什么会错误

img

顺序不对, 第二行还没有B类,也就没有B类成员函数.所以friend函数应报错.

#include <iostream>

struct A;

struct B
{
    B();

    void lookA();

  private:
    A *p;
};

struct A
{
    friend void B::lookA();

    A() = default;

  private:
    int a = 10;
    int b = 20;
};

B::B()
    : p(new A)
{}

void B::lookA()
{
    std::cout << p->a << std::endl;
    std::cout << p->b << std::endl;
}

auto main() -> int
{
    B test;
    test.lookA();

    return 0;
}


修改如下,供参考:

#include <iostream>
using namespace std;
class A;            //修改
class B{
    private:
        A* p;
    public:
        B();//{p = new A;}修改
        void lookA();   //修改
};

class A{
    friend void B::lookA();
    public:
        A(){a = 10; b = 20;}
    private:
        int a;
        int b;
};

B::B()  //修改
{
    p = new A;
}
void B::lookA() //修改
{
    cout<<p->a<<endl;
    cout<<p->b<<endl;
}
int main()
{
    B temp;
    temp.lookA();

    return EXIT_SUCCESS;
}