3

consider these c++ fragments:

foo.h:

class foo
{
bar myobj;
};

bar.h:

class bar
{
foo *yourobj;
};

other file:

#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?

4

2 回答 2

7

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

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

例如在foo.h

class foo_members;

class foo
{
    foo_members* opaque;
};

而在foo.cpp

#include "bar.h"
class foo_members{
    bar mybar;
};
于 2012-09-06T01:31:08.490 回答
1

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

[类.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;
}
于 2012-09-06T01:44:39.000 回答