【问题标题】:friend member function in C++ - forward declaration not workingC ++中的朋友成员函数 - 前向声明不起作用
【发布时间】:2014-02-18 10:06:08
【问题描述】:

我遇到的情况类似于Specify a class member function as a friend of another class? 中描述的情况。

但是,就我而言,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(); } 
};

感谢帮助!

(顺便说一句,这是我的第一个问题,我希望我解释清楚)

【问题讨论】:

  • 如果你用代码示例说明这一点会更容易提供帮助。
  • Friend 成员函数违反了封装的范式。如果您给出确切的问题,我相信,会有比朋友成员更好的解决方案。
  • 嘿 juanchopanza,对不起 - 我现在添加了一个代码示例! user1767754 - 我需要使用 A 的一些内部功能,并且我想确保 B 中的其他功能不会意外使用 fA_protected。
  • 我只遇到过一个案例,我们不得不在 10 年的编程中使用朋友,我很确定原因是因为要正确编写一些东西需要太多的工作
  • 您可以将A a 更改为std::unique_ptr<A> a 吗?这将打破循环依赖并解决您的问题。

标签: c++ friend circular-dependency friend-function


【解决方案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(); } 

【讨论】:

    猜你喜欢
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多