c++ - 循环依赖和函数

标签 c++

我有两个标题,A 和 B。它们看起来像这样:

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

class A {
    // stuff
    AFunction(B* b);
    OtherFunction();
}

// B.h
class A;

BFunction(A* a);

这是我第一次尝试解决循环依赖,所以我不太确定我在做什么。我的问题如下:BFunction 在某些时候调用 a->OtherFunction();。我得到一个错误,因为 OtherFunction 没有前向声明,显然我也不能前向声明它。这种情况是对称的(AFunction 调用 b->SomeOtherFunction()),所以我无法通过交换 include 和 forward 声明来修复它。

我该如何解决?

最佳答案

如果您需要有关 A 或 B 的任何信息,而不仅仅是分配它们类型的指针,那么您必须将相关代码移动到 .cpp 文件中,因为您不能将它们包含在循环中方式。解决方法如下:

啊啊

class B; // forward declaration

class A {
  B* b;

  // legal, you don't need to know anything about B
  void set(B* b) { this->b = b; } 

  // must be implemented in .cpp because it needs to know B
  void doSomethingWithB(); 
};

A.cpp

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

void A::doSomethingWithB() {
  b->whatever();

B.h

class A

class B {
  void methodWithA(A* a);
};

B.cpp

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

void B::methodWithA(A* a) {
  a->whatever();
}

关于c++ - 循环依赖和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14168737/

相关文章:

c++ - 创建用户在 C++ 中定义的星星对角线

c++ - 如何在 C/C++ 中进行更多预处理

c++ - 比 Stackwalk 快

c++ - 如何使用 FFTW 进行频谱分析?

C++ vector of priority_queue of strings with custom strings comparator

c++ - 有符号和无符号之间的减法,然后是除法

c++ - boost::spirit::qi Expectation Parser 和分组意外行为的解析器

c++ - QTreeWidgterItem - 隐藏值或附加属性

c++ - 正在分配指针的测试类析构函数?

c++ - 在 C++ 中何时返回指针、标量和引用?