friend member function in C++ - forward declaration not working

烈酒焚心 提交于 2019-12-02 11:57:44

If you can change B to take a pointer on A, following may help: (I use raw pointer as you can't use smart pointer according to comment).

//A.h
#include "B.h"

class A
{
public:
    friend void B::fB();
    void fA() {};
protected:
    void fA_protected(){};
};

//B.h
class A; // forward declaration

class B
{
private:
    A* a;

public:
    B();
    ~B();                       // rule of 3
    B(const B& b);              // rule of 3
    B& operator = (const B&);   // rule of 3

    void fB(); // this function should call the protected function
    void fB2(); 
};

//B.cpp

#include "B.h"
#include "A.h"

B::B() : a(new A) {}
B::~B() { delete a; }                      // rule of 3
B::B(const B& b) : a(new A(*b.a)) {}       // rule of 3
B& B::operator = (const B&) { *a = *b.a; return *this; } // rule of 3

void B::fB() { a->fA_protected();}
void B::fB2() { a->fA(); } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!