在C ++中处理共同依赖类的最好方法是什么? [英] What is the best way to deal with co-dependent classes in C++?
问题描述
说我有一个类foo,其中有一个类bar的对象作为成员
Say I have a class foo with an object of class bar as a member
class foo
{
bar m_bar;
};
现在假设bar需要跟踪拥有它的foo。
Now suppose bar needs to keep track of the foo that owns it
class bar
{
foo * m_pfoo;
}
这两个类相互引用,没有前向声明,所以在foo的声明之前添加这一行解决了这个问题
The two classes reference each other and without a forward declaration, will not compile. So adding this line before foo's declaration solves that problem
class bar;
现在,这里是问题 - 当写头文件时,每个 >依赖于另一个:foo.h需要bar.h中的定义,反之亦然。
Now, here is the problem - when writing the header files, each header depends on the other: foo.h needs the definitions in bar.h and vice-versa. What is the proper way of dealing with this?
推荐答案
您需要将所有成员访问权移出标题, 。
You need to move all of the member access out of the header, and into your source files.
这样,您可以在标题中转发声明的类,并在foo中定义它们:
This way, you can forward declare your classes in the header, and define them in foo:
// foo.h
class bar;
class foo {
bar * m_pbar;
}
// bar.h
class foo;
class bar {
foo * parent;
}
这将允许你工作 - 成员信息到您的头中 - 将其移动到.cpp文件。 .cpp文件可以包括foo.h和bar.h:
That will allow you to work - you just can't put definitions that require member information into your header - move it to the .cpp file. The .cpp files can include both foo.h and bar.h:
// Foo.cpp
#include "foo.h"
#Include "bar.h"
void foo::some_method() {
this->m_pbar->do_something(); // Legal, now, since both headers have been included
}
这篇关于在C ++中处理共同依赖类的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!