0

我遇到的情况类似于将类成员函数指定为另一个类的朋友?.

但是在我的情况下,B 类需要知道 A 类,因为它正在使用它,所以该线程中给出的解决方案对我不起作用。我还尝试对函数本身进行前向声明,但效果不佳。似乎每个类都需要其他类的完整定义......

有什么简单的方法可以解决吗?我更喜欢不涉及包装旧类之一的新类的解决方案。

代码示例:

//A.h
class B; //not helping
void B::fB(); //not helping

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

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

class B
{
private:
    A a;

public:
    void fB(){ a.fA_protected();} // this function should call the protected function
    void fB2(){ a.fA(); } 
};

感谢帮助者!

(顺便说一下这是我的第一个问题,我希望我能清楚地解释自己)

4

1 回答 1

1

如果您可以更改 B 以在 A 上获取指针,则以下可能会有所帮助:(我使用原始指针,因为根据评论您不能使用智能指针)。

//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(); } 
于 2014-02-18T12:29:06.860 回答