在 C++ 中处理相互依赖的类的最佳方法是什么?

编程入门 行业动态 更新时间:2024-10-20 20:52:50
本文介绍了在 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++ 中处理相互依赖的类的最佳方法是什么?

本文发布于:2023-11-26 13:13:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633997.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:相互依赖   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!