I've been trying some examples in a book (C++ Primer by Stanley Lippman) and I understand that a class can make another class its friend (to access some private members). Now I'm reading about a member function being a friend and I try the example
class Screen
{
public:
friend void Window_mgr::clear();
typedef std::string::size_type pos;
Screen () = default;
Screen (pos ht, pos wd, char c) : height (ht), width (wd),
contents (ht * wd, c) { }
private:
void do_display (std::ostream &os) const
{
os << contents;
}
pos cursor = 0;
pos height = 0, width = 0;
pos test_num = 100, test_num2 = 222;;
std::string contents = "contents";
};
class Window_mgr {
public:
using ScreenIndex = std::vector<Screen>::size_type;
void clear (ScreenIndex);
private:
std::vector <Screen> screens {Screen (24, 80, ' ')};
};
void Window_mgr::clear(ScreenIndex i)
{
Screen &s = screens[i];
s.contents = std::string(s.height * s.width, ' ');
}
but it produces a compiler error saying
Window_mgr has not been declared
and then I read this:
• First, define the Window_mgr class, which declares, but cannot define, clear. Screen must be declared before clear can use the members of Screen.
• Next, define class Screen, including a friend declaration for clear.
• Finally, define clear, which can now refer to the members in Screen.
I don't understand this part -- can someone explain?