类互相依赖 [英] classes depend on each other

查看:93
本文介绍了类互相依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下c ++片段:

consider these c++ fragments:

foo.h:

class foo
{
bar myobj;
};

bar.h:

class bar
{
foo *yourobj;
};

其他文件:

#include "foo.h" //because foo.h is included first bar will not be defined in foo.h
#include "bar.h"

foo container;

bar blah;

我知道我并没有为编写构造函数之类的东西而烦恼,但您明白了.有谁知道纠正这种情况的方法?

I know I didn't bother to write constructors and all that but you get the idea. Anyone know a way to remedy this situation?

推荐答案

有几种常用的技术可以做到这一点.

There are several common techniques to do this.

首先,请尽可能使用前向声明. 其次,如果循环依赖关系的一部分依赖于类中的函数,则使该类继承自提供这些函数声明的接口"类. 最后,使用PIMPL(指向实现细节的指针).不必列出类声明中的所有字段,只需包含一个指向实际类数据的指针即可.

First, use forward declarations when you can. Second, if part of the circular dependency depends on functions in a class, make that class inherit from an "interface" class which provides declarations of those functions. Lastly, use PIMPL (pointer to implementation details). Instead of listing all the fields in the class declaration, just include a pointer to the actual class data.

例如foo.h

class foo_members;

class foo
{
    foo_members* opaque;
};

foo.cpp

#include "bar.h"
class foo_members{
    bar mybar;
};

这篇关于类互相依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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