Chapter 7.3.4 of the book C++ Primer mentions forward declarations and specifying member function friends. It states that specifying member function friends requires careful structuring to accommodate interdependencies among the declarations and definitions. When I strip all the fluff, this is the result:
#include <string>
#include <vector>
class Screen;
class Window_mgr {
public:
using ScreenIndex = std::vector<Screen>::size_type;
void clear(ScreenIndex);
private:
std::vector<Screen> screens;
};
class Screen {
friend void Window_mgr::clear(ScreenIndex);
public:
using pos = std::string::size_type;
private:
pos height{0},
width{0};
std::string contents;
};
inline void Window_mgr::clear(ScreenIndex i) {
Screen& s = screens[i];
s.contents = std::string(s.height * s.width, ' ');
}
My understanding is that classes go into their own header files. If that is the case, how do I separate these? I checked out some of the questions on Stack Overflow, but did not find the answer I am looking for.
Edit: this is how I was able to strip up the code, but I'm still unsure whether this is good of bad practice and whether this is even maintainable.
window_mgr.h
#ifndef WINDOW_MGR_H
#define WINDOW_MGR_H
#include <vector>
class Screen;
class Window_mgr {
public:
using ScreenIndex = std::vector<Screen>::size_type;
void clear(ScreenIndex);
private:
std::vector<Screen> screens;
};
#endif
screen.h
#ifndef SCREEN_H
#define SCREEN_H
#include <string>
#include "window_mgr.h"
class Screen {
friend void Window_mgr::clear(ScreenIndex);
public:
using pos = std::string::size_type;
private:
pos height{0},
width{0};
std::string contents;
};
#endif
window_mgr.cpp
#include "window_mgr.h"
#include "screen.h"
inline void Window_mgr::clear(ScreenIndex i) {
Screen& s = screens[i];
s.contents = std::string(s.height * s.width, ' ');
}