The following describes how to organize header files when two classes contain each other using C ++.
For example, if Cat is a class and dog is a class, cat must have a member variable.
dog* doggy
Dog has member variables
cat* catty
In fact, four files can be handled:
//cat.h#pragma onceclass dog;class cat{ public: dog *doggy; dog* getDoggy();}; //dog.h#pragma onceclass cat;class dog{ public: cat *catty; cat* getCatty();}; //cat.cpp#include "cat.h"#include "dog.h"dog* cat::getDoggy(){ doggy = new dog(); return doggy;} //dog.cpp#include "dog.h"cat* dog::getCatty(){ return catty;}
Principles of header file organization:
- Non-template class declarations and definitions are separated. Put the Declaration in. H, and put the definition in. cpp;
- Prevent repeated header files. There are two methods, one is
#pragma once
The other is
#ifndef...#define...#endif
3. Use Forward Declaration instead of # include as much as possible when the custom header files are interdependent. For example, in cat. H above
class dog;
Change
#include "dog.h"
It is also compiled. However, if the method is also changed in dog. H, it will fail. This problem is not solved with the forward statement.
At this time, the header file organization does not conflict with the above type, and the. cpp file can be used only.
Note. Cat. cpp must contain dog. H because the constructors of the Dog class are called.
References:
Http://blog.csdn.net/lainegates/article/details/7696176