[英]Why forward declaration and pointer (or reference?) can resolve circular dependency?
I know circular dependency can be resolved by forward declaration and pointer like this: 我知道循环依赖可以通过前向声明和指针来解决,如下所示:
Ah 啊
class B;
class A{
public:
void update(B* b);
void test(){}
};
A.cpp A.cpp
#include "A.h"
#include "B.h"
void A::update(B* b){
b->test();
}
Bh BH
class A;
class B{
public:
void update(A* a);
void test(){}
};
B.cpp B.cpp
#include "B.h"
#include "A.h"
void B::update(A* a){
a->test();
}
so that the code above can compile with containing each other,but the problem is, why can it be said as "resolving circular dependency"? 这样上面的代码可以相互包含,但是问题是,为什么可以说它是“解决循环依赖”? I was not satisfying that "B" still exists in source code of A and "A" still exists in source code of B. At least I think it should change the design pattern so that no class can contain each other,eg,using a parent class to hold A and B.:
我不满意A的源代码中仍然存在“ B”而B的源代码中仍然存在“ A”。至少我认为它应该更改设计模式,以使任何类都不能相互包含,例如,使用a持有A和B的父类:
Parent.h Parent.h
class A;
class B;
class Parent{
void update(A* a,B* b);
};
Parent.cpp Parent.cpp
void Parent::update(A* a,B* b){
a->test();
b->test();
}
why using forward declaration and pointer can said to be "resolve circular dependency" even the source code still contains each other? 为什么即使源代码仍然包含彼此,使用前向声明和指针也可以说是“解决循环依赖关系”?
When you have Ah with the line: 当您在行中有Ah时:
#include "B.h"
and Bh with the line: 和Bh一行:
#include "A.h"
there is a circular dependency between Ah and Bh When two header files are circularly dependent, it creates problems at compile time. Ah和Bh之间存在循环依赖关系当两个头文件循环依赖时,会在编译时产生问题。 You can avoid them by using forward declarations.
您可以通过使用前向声明来避免它们。
It does not preclude A.cpp with lines: 它不排除A.cpp带有行:
#include "A.h"
#include "B.h"
and 和
B.cpp with lines: B.cpp用行:
#include "A.h"
#include "B.h"
Implementation of A
can depend on the definitions of A
as well as B
. A
实现可以取决于A
和B
的定义。
Implementation of B
can depend on the definitions of A
as well as B
. B
实现可以取决于A
和B
的定义。
In that case, the classes are circularly dependent but not in the same sense two header files can be circularly dependent. 在那种情况下,这些类是循环相关的,但从不同的意义上讲,两个头文件可以是循环相关的。
Forward declaring a pointer resolves the circular dependency, because the compiler doesn't need to know the content of the struct or class to be pointed. 前向声明指针可解决循环依赖性,因为编译器不需要知道要指向的结构或类的内容 。 It needs to know the size of some pointer
sizeof *p == sizeof void *
to be inserted, and which will have the correct semantics after both classes or structs have been fully defined. 它需要知道要插入的某些指针的
sizeof *p == sizeof void *
,并且在完全定义了两个类或结构之后 ,它将具有正确的语义。
A counter example is: 一个反例是:
struct A { struct B b; }; struct B { struct A a; };
Even when one or both of those structs was forward declared, the content would have to be known before the closing brace '}'. 即使预先声明了其中一个或两个结构,也必须在右括号“}”之前知道其内容。 This "clearly" isn't the case.
事实并非如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.