Today in the 7th chapter of C + + primer, an exercise is to write two classes, one is the screen class, and the Window_mgr class, where the Window_mgr class contains a member of a vector<screen> type and a clear function, To manipulate the screen class, you need to declare the clear function as a friend function of the screen class, so that you need to include the header file of the Window_mgr class in the header file that defines the screen class, as well as the Window_mgr class to include the header file of the screen class. As follows:
Screen.h
#ifndef screen_h#define screen_h#include "Window_mgr.h" class Screen{friend void Window_mgr::clear (); ...}; #endif
Window_mgr.h
#ifndef window_mgr_h#define window_mgr_h#include "screen" class window_mgr{public:void clear () ... private: vector<screen> screens;}; #endif
main.cc
#include "window_mgr.h" #include "Screen.h" int main () {... return 0;}
At the beginning, according to the above way of writing, compile error, said in the Screen.h file window_mgr undefined.
The reasons are as follows:
According to the above notation, before compiling, the main.cc file will become as follows:
#define Window_mgr_h#define screen_hclass screen{friend void Window_mgr::clear (), ...}; Class Window_mgr{public:void Clear ();........private:vector<screen> screens;};
Obviously the definition of window_mgr is behind friend void Window_mgr::clear (), so there is an error.
Therefore, before the declaration of the clear function, you should add the predecessor declaration of the Window_mgr class. Class Window_mgr;
Modify the Screen.h file as follows:
#ifndef screen_h#define screen_hclass window_mgr;class screen{friend void Window_mgr::clear (), ...}; #endif
This will allow for normal compilation.
Summary: Special care needs to be taken to ensure that the header files are included with each other and that it has been declared before using a class or function.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + header files have problems with each other