What is the best way to deal with co-dependent classes in C++?(在 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;
现在,问题来了——在编写头文件时,每个 header 都依赖于另一个: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++ 中处理相互依赖的类的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中处理相互依赖的类的最佳方法是什么?


基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05