在 C++ 中处理相互依赖的类的最佳方法是什么? [英] What is the best way to deal with co-dependent classes in C++?

查看:26
本文介绍了在 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++ 中处理相互依赖的类的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆