gpt4 book ai didi

c++ - 循环依赖和函数

转载 作者:太空宇宙 更新时间:2023-11-04 12:00:51 25 4
gpt4 key购买 nike

我有两个标题,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com