When constructing your own class, it is possible to encounter mutual reference problems between the two classes, for example: a type defined in Class A class b,a is used and a type defined by a is used in B.
For example:
Cup.h
#ifndef Cup_h #define Cup_h"Box.h"class cup{ public: ~Cup (); Box b; Cup ();}; #endif // Cup_h
Cup.cpp
" Cup.h " <iostream>usingnamespace std; Cup::cup () { "Cup cons" << Endl;} Cup::~Cup () { "Cup des" << Endl;}
Box.h
#ifndef Box_h #define Box_h"Cup.h"class box{ public: Box (); ~Box (); Cup Cup;}; #endif // Box_h
Box.cpp
" Box.h " <iostream>usingnamespace std; Box::box () { "box cons" << Endl;} Box::~box () { "box des" << Endl;}
In this case, think of a b.cup.b.cup.b ..., which is defined in a way that is similar to a dead loop in a program. The compiler will definitely make an error.
My error message is
Include\cup.h|10|error: ' Box ' does not name a type|
So, in general, the definition of both, at least one side uses pointers, or both use pointers, but must not define entity objects.
To get to the end, then, in the definition of mutual references will definitely need to include header files, if only in their own header file contains the other side of the header file, is not compiled, as shown in the above case
Solution, let one (for example, CUP) only declare the other Party (class box;) and use the pointer (box *b), and do not include the header file Box.h, in the implementation file (Cup.cpp) file contains Box.h, the modified code is as follows:
Cup.h
#ifndef Cup_h #define Cup_hclass Box; class cup{ public: void createbox (); ~Cup (); *b; Cup ();}; #endif // Cup_h
Cup.cpp
#include"Cup.h"#include<iostream>#include"Box.h"using namespacestd; Cup::cup (): B (NULL) {cout<<"Cup Cons"<<Endl;} Cup::~Cup () {if(b!=NULL) Delete B; cout<<"Cup des"<<Endl;}voidCup::createbox () {b=NewBox ();}
Note Why not in Cup::cup () Direct B = new box (), because this is a dead loop, direct StackOverflow, so use the Createbox ()
Finally write a main.cpp to test, you can try to explain the results of the operation
" Box.h " "Cup.h"<iostream>usingnamespace std; int Main () { Box b; " something in the middle " << Endl; Cup C; C.createbox ();}
The problem of two classes in C + + with each other