课程相互依赖

时间:2012-09-06 01:28:23

标签: c++ oop class

考虑这些c ++片段:

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;

我知道我没有费心去编写构造函数,但是你知道了。有人知道如何解决这种情况吗?

2 个答案:

答案 0 :(得分:7)

有几种常用技巧可以做到这一点。

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

例如在foo.h

class foo_members;

class foo
{
    foo_members* opaque;
};

并在foo.cpp

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

答案 1 :(得分:1)

另一种方法是只制作一个声明所有类的标题。

[classes.h]

class foo;
class bar;

class foo
{
    bar *FoosBar;
    int FooFunc(void);
};

class bar
{
    foo *BarsFoo;
    bool BarFunc(void);
}

[Foo.cpp中]

#include "classes.h"

int foo::FooFunc(void)
{
    // Reference FoosBar somewhere here or something maybe
    return 7;
}

[bar.cpp]

#include "classes.h"

bool bar::BarFunc(void)
{
    // Reference BarsFoo somewhere here or something maybe
    return true;
}