课程相互依赖

Pgr*_*rAm 2 c++ oop class

考虑这些c ++片段:

foo.h中:

class foo
{
bar myobj;
};
Run Code Online (Sandbox Code Playgroud)

bar.h:

class bar
{
foo *yourobj;
};
Run Code Online (Sandbox Code Playgroud)

其他档案:

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

foo container;

bar blah;
Run Code Online (Sandbox Code Playgroud)

我知道我没有费心去编写构造函数,但是你得到了这个想法.有人知道解决这种情况的方法吗?

Ant*_*ony 7

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

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

例如在 foo.h

class foo_members;

class foo
{
    foo_members* opaque;
};
Run Code Online (Sandbox Code Playgroud)

并在 foo.cpp

#include "bar.h"
class foo_members{
    bar mybar;
};
Run Code Online (Sandbox Code Playgroud)