Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

header - What is the best way to deal with co-dependent classes in C++?

Say I have a class foo with an object of class bar as a member

class foo
{
    bar m_bar;
};

Now suppose bar needs to keep track of the foo that owns it

class bar
{
    foo * m_pfoo;
}

The two classes reference each other and without a forward declaration, will not compile. So adding this line before foo's declaration solves that problem

class bar;

Now, here is the problem - when writing the header files, each header depends on the other: foo.h needs the definitions in bar.h and vice-versa. What is the proper way of dealing with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to move all of the member access out of the header, and into your source files.

This way, you can forward declare your classes in the header, and define them in foo:

// foo.h
class bar;

class foo {
    bar * m_pbar;
}

// bar.h
class foo;
class bar {
    foo * parent;
}

That will allow you to work - you just can't put definitions that require member information into your header - move it to the .cpp file. The .cpp files can include both foo.h and bar.h:

// Foo.cpp
#include "foo.h"
#Include "bar.h"

void foo::some_method() {
     this->m_pbar->do_something(); // Legal, now, since both headers have been included
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...