Member function as a friend in another class
Good afternoon. A Happy New Year, I wish you. (Yoda's style).
I'm trying to do this:
Code:
class Screen {
// Window_mgr::clear must have been declared before class Screen
friend void Window_mgr::clear(ScreenIndex);
// ... rest of the Screen class
};
But Screen won't be recognized if I put the WindowMgr declaration above that class. So for now, the code is structured like this:
Code:
#ifndef SCREEN00_H_
#define SCREEN00_H_
#include <string>
#include <vector>
using std::string;
using std::vector;
class Screen
{
friend class WindowMgr;
public:
typedef string::size_type pos;
Screen() = default;
Screen(pos ht = 0, pos wd = 0) : cursor(0), height(ht),
width(wd), contents(ht * wd, ' ') {}
Screen(pos ht, pos wd, char c) : height(ht), width(wd),
contents(ht * wd, c) {}
char get() const { return contents[cursor]; }
inline char get(pos r, pos c) const
{
pos row = r * width;
return contents[row + c];
}
inline Screen& move(pos r, pos c)
{
pos row = r * width; // compute the row location
cursor = row + c; // move cursor to the column within that row
return *this; // return this object as an lvalue
}
inline void someMember() const { ++access_ctr; }
inline Screen& set(char c)
{
contents[cursor] = c;
return *this;
}
inline Screen& set(pos r, pos col, char ch)
{
contents[r*width + col] = ch;
return *this;
}
Screen& display(std::ostream& os)
{
do_display(os);
return *this;
}
const Screen& display(std::ostream& os) const
{
do_display(os);
return *this;
}
private:
mutable size_t access_ctr;
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
void do_display(std::ostream& os) const
{
os << contents;
}
};
class WindowMgr
{
public:
using ScreenIndex = std::vector<Screen>::size_type;
void clear(ScreenIndex);
private:
std::vector<Screen> screens{Screen(24, 80, ' ') };
};
#endif
Code:
#include "Headers/screen00.h"
#include <string>
using std::string;
void WindowMgr::clear(ScreenIndex i)
{
// s is a reference to the Screen we want to clear
Screen &s = screens[i];
// reset the contents of that Screen to all blanks
s.contents = string(s.height * s.width, ' ');
}
Code:
#include "Headers/screen00.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
Screen myScreen(5,3);
// move the cursor to a given position, and set that character
myScreen.move(4,0).set('#');
Screen nextScreen(5, 5, 'X');
nextScreen.move(4,0).set('#').display(cout);
cout << "\n";
nextScreen.display(cout);
cout << endl;
const Screen blank(5, 3);
myScreen.set('#').display(cout); // calls nonconst version
cout << endl;
blank.display(cout); // calls const version
cout << endl;
return EXIT_SUCCESS;
}