This article attempts to explain the example of C + + primer screen and window_mgr, why is it possible to put two classes in two files that cannot be compiled?
Write two classes in the same file, explaining the problem in three examples:
The first is a question of wording:
When compiling to screen, because the screen class uses the member function to Window_mgr, although the Window_mgr declaration is given earlier, the full definition of window_mgr is also clear, so the compilation error.
Class Window_mgr
Class screen
{
Public
Friend window_mgr& Window_mgr::relocate (Window_mgr::index R, Window_mgr::index C, screen& s);
Private
int height;
int width;
}
Class Window_mgr
{
Public
typedef STD::STRING::SIZE_TYPE Index;
window_mgr& window_mgr::relocate (Index R, index C, screen& s)
{
S.height + = r;
S.width + = C;
return *this;
}
}
The second way of writing the question is:
When compiling to relocate, because the implementation of screen& S is used to the member variable of screen, although the previous screen's declaration, but also clear the full definition of screen, so the compilation error.
Class screen;
Class Window_mgr
{
Public
typedef STD::STRING::SIZE_TYPE Index;
window_mgr& window_mgr::relocate (Index R, index C, screen& s)
{
S.height + = r;
S.width + = C;
return *this;
}
}
Class screen
{
Public
Friend window_mgr& Window_mgr::relocate (Window_mgr::index R, Window_mgr::index C, screen& s);
Private
int height;
int width;
}
The third type of notation:
Moving the implementation of window_mgr::relocate to the end, the problem is solved because the implementation details of the screen&s are not required for compiling the class Window_mgr
Class screen;
Class Window_mgr
{
Public
typedef STD::STRING::SIZE_TYPE Index;
window_mgr& window_mgr::relocate (Index R, index C, screen& s);
}
Class screen
{
Public
Friend window_mgr& Window_mgr::relocate (Window_mgr::index R, Window_mgr::index C, screen& s);
Private
int height;
int width;
}
window_mgr& Window_mgr::relocate (Window_mgr::index R, Window_mgr::index C, screen& s)
{
S.height + = r;
S.width + = C;
return *this;
}
It can be seen that these two classes require a strict alternating order if the compilation succeeds
This also explains why it is not possible to compile in two files.
Appendix:
The first implementation of the two files that cannot be compiled
The implementation is as follows: Window_mgr.h
#ifndef window_mgr//In order to avoid nesting of two files
#define Window_mgr
#include <string>
#include <Screen.h>
Class Window_mgr
{
Public
typedef STD::STRING::SIZE_TYPE Index;
window_mgr& window_mgr::relocate (Index R, index C, screen& s)
{
S.height + = r;
S.width + = C;
return *this;
}
}
#endif
Screen.h
#ifndef screen
#define Screen
#include "Window_mgr.h"
Class screen
{
Public
Friend window_mgr& Window_mgr::relocate (Window_mgr::index R, Window_mgr::index C, screen& s);
Private
int height;
int width;
}
#endif