classes depend on each other

2020-03-28 22:37发布

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?

标签: c++ oop class
2条回答
冷血范
2楼-- · 2020-03-28 22:57

Another way would be to make only one header that declares all your classes.

[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;
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-03-28 23:03

There are several common techniques to do this.

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.

For example in foo.h

class foo_members;

class foo
{
    foo_members* opaque;
};

And in foo.cpp

#include "bar.h"
class foo_members{
    bar mybar;
};
查看更多
登录 后发表回答