Conclusion classes in C ++

I need to create two classes that use each other.

For instance:

Class A contains objects of type Class B , and Class B contains objects of type Class A

But when I compile, this is what happens: "error: ISO C ++ prohibits declaring" Maps "without type"

I changed my classes to save the header file (.h), but it was not allowed.

This may be the main question, but I don’t know the google search keyword ...

code:

Cell.h:

 Class Cell { public: Map *map; } 

Map.h:

 Class Map { public: Cell *cell; } 
+4
source share
3 answers

If class A contains class B , and class B also contains class A , then no, you cannot do this.

 class B; // forward declaration of name only. Compiler does not know how much // space a B needs yet. class A { private: B b; // fail because we don't know what a B is yet. }; class B { private: A a; }; 

Even if this works, there will be no way to create an instance.

 B b; // allocates space for a B // which needs to allocate space for its A // which needs to allocate space for its B // which needs to allocate space for its A // on and on... 

However, they may contain pointers (or links) to each other.

 class B; // forward declaration tells the compiler to expect a B type. class A { private: B* b; // only allocates space for a pointer which size is always // known regardless of type. }; class B { private: A* a; }; 
+1
source

You want to forward the declaration and signposts.

 //ah class B; //forward declare than a class B, exist somewhere, although it is not completely defined. class A{ map<string,B*> mapOfB; }; //bh class A; //forward declare than a class A, exist somewhere, although it is not completely defined. class B{ map<string,A*> mapOfA; } 

and in your .cxx you would include the necessary headers

 //a.cxx #include "bh" A::A(){ /* do stuff with mapOfB */ } //b.cxx #include "ah" B::B(){ /* do stuff with mapOfA */ } 
+3
source

The problem in your case is that you have a recursive version. Cell.h includes Map.h , which includes Cell.h Instead of just including this forward, declare the classes:

In Cell.h :

 class Map; class Cell { // ... } 

In Map.h :

 class Cell; class Map { // ... } 
+2
source

Source: https://habr.com/ru/post/1487528/


All Articles