Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new to C++, so this question may be basic:

I have two classes that need to refer to each other. Each is in its own header file, and #include's the other's header file. When I try to compile I get the error "ISO C++ forbids declaration of ‘Foo’ with no type" for one of the classes. If I switch things so the opposite header gets parsed first I get the same error with the other class.

Is it possible in C++ to have two classes that need references to each other?

For more detail: I have an "App" class and a "Window" class. App needs to refer to Window to make the window. Window has a button that calls back to App, so it needs a reference to App. If I can't have two classes refer to each other, is there a better way to implement this?

See Question&Answers more detail:os

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

1 Answer

You can use forward declarations in the header files to get around the circular dependencies as long as you don't have implementation dependencies in the headers. In Window.h, add this line:

class App;

In App.h, add this line:

class Window;

Add these lines before the class definitions.

Then in the source files, you include the headers for the actual class definitions.

If your class definitions reference members of the other class (for example, in inlines), then they need to be moved to the source file (no longer inline).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...