#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Screen;
class Window_mgr
{
private:
vector<Screen> screens;
public:
using Screen_index = vector<Screen>::size_type;
void clear(Screen_index i);
Window_mgr() = default;
};
class Screen
{
friend void Window_mgr::clear(Screen_index i);
public:
using pos = string::size_type;
mutable unsigned counter = 0;
//constructors
Screen() = default;
Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht*wd, c) {}
//operations
char get() const { return contents[cursor]; }
inline char get(pos ht, pos wd) const;
Screen &move(pos r, pos c);
Screen &set(char);
Screen &set(pos, pos, char);
//output methods
Screen &display(ostream &os) { do_display(os); return *this; }
const Screen &display(ostream &os) const { do_display(os); return *this; }
private:
pos cursor = 0;
pos height = 0, width = 0;
string contents;
void do_display(ostream &os) const { os << contents; }
};
char Screen::get(pos r, pos c) const
{
return contents[r*width + c];
}
inline Screen &Screen::move(pos r, pos c)
{
cursor = r*width + c;
return *this;
}
inline Screen &Screen::set(char c)
{
contents[cursor] = c;
return *this;
}
inline Screen &Screen::set(pos r, pos c, char ch)
{
contents[r*width + c] = ch;
return *this;
}
void Window_mgr::clear(Screen_index i)
{
Screen &s = screens[i];
s.contents = string(s.height*s.width, ' ');
}
int main(int argc, char *argv[])
{
//some operations omitted ...
system("pause");
return 0;
}
对于成员函数作为友元的依赖关系:
1、先定义Window_mgr类,其中声明clear函数,但不能定义它。在clear使用Screen的成员之前必须先声明clear。
2、接下来定义Screen,其中包括对于clear的友元声明。
3、最后定义clear,此时它才可以使用Screen的成员。