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
280 views
in Technique[技术] by (71.8m points)

c++ - Complex circular dependency

what is the the best practice of solving circular dependency in C++?

I could use the forward declaration, but then I get the pointer to incomplete class type is not allowed error. Does that mean that two classes that uses each others pointer cannot be dependent?

Also, I thought about forward declaring each class and then including every header of the solution in the main.cpp, so it's all in one place. Would you recommend it?

A snippet from the whole project is below, so you can refer to it if the issue is better explained on an example I'm familiar with, but it would do just to be theoretical. Thanks

Models depending on each other

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You just need to use forward declaration correctly:

  1. Put all code in cpp files
  2. Put just class declaration in header file
  3. In header file:
    1. Use forward declaration if you only use a pointer or a reference.
    2. Otherwise you to include header file. (Do Not add unrequired includes)
  4. In cpp file
    1. include all header files you require.

Note: Add include guards.

Its hard to actually do it without the actual declarations. The diagram is nice but does not have enough information. A picture may be worth a thousand words, but a precisely defined language can convey more exact information very compactly (unlike English and its inconsistencies).


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

...