如何解决具有父类和子类设置的 C++ 循环依赖
C++ 中的循环依赖问题似乎是初学者的常见问题。我查看了无数案例和对这些案例的解释,但找不到将修复程序应用于我的特定案例的方法。
程序设置和我的目标
假设我有两个类 - Grid
和 Cell
。在父子范式中,Grid
是一个比喻性的父对象,其中包含多个子 Cell
对象。
Cell
必须能够访问其自己的父级 Grid
,而 Grid
必须能够访问其子级 Cell
中的任何一个。
我目前按如下方式实现(注意我删除了不相关的成员和参数)。
Grid.h 和 Grid.cpp
// == Grid.h == //
#include "Cell.h"
class grid
{
private:
std::vector<std::unique_ptr<cell>> cells; // vector of pointers to child cells
public:
void add_cell(grid *parent_grid,[params...]) {cells.push_back(std::make_unique<cell>(parent_grid,[params...])};
}
Cell.h 和 Cell.cpp
// == Cell.h == //
class grid; // forward-declaration?
class cell
{
private:
grid *parent = nullptr;
public:
cell(grid *parent_grid,[params...]);
}
// == Cell.cpp == //
cell::cell(grid *parent_grid,[params...])
{
parent = parent_grid; // Assign the parent pointer to point to the set parent.
}
Main.cpp
#include "Grid.h"
int main()
{
...
}
问题
这一直有效,直到 Cell
尝试访问其父 Grid
的成员方法,例如:
[... inside a Cell member method ...]
(*parent)->grid_maintenance_method();
我立即收到以下错误:error: incomplete definition of type 'grid'
。
我该如何解决这个循环依赖问题?显然,前向声明对于父 Grid 的基本表示已经足够了,但还不够,因为我无法访问父 Grid 对象。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。