问题描述:

This question already has an answer here:

  • Resolve header include circular dependencies

    8 answers

网友答案:

The problem in this code is that your Topology (Topology.h) uses Router objects passed by value: the compiler needs to have the full definition of Router. That's fine, so you include Router.h. However, your Router needs a full Topology object (not a pointer, not a reference) to work.

So you have a configuration where A needs B fully declared to be fully declared, and B needs A fully declared to be fully declared itself. That's a problem, as stated in comments, of Circular Dependencies.

What you should do is to avoid the Topology object in Router (you may need a pointer because a full object means copy and not shared instance). Use a forward declaration of Topology in Router.h (and #include "Topology" in Router.cpp) and declare your "topology" attribute as pointer/smart pointer/reference.

网友答案:

router.h includes topology.h which skips including router.h due to include guards and then uses class Router in its definition which is not defined. The standard solution is to forward declare types (such as class Router;). Unfortunately std::map requires full types and using it with incomplete types is undefined behavior. To make the map compatible with incomplete types you can either use std::unique_ptr<map<Router, int>> (or some other pointer type) or boost::container::map<Router, int>>.

相关阅读:
Top