C++ Primer 练习7.32(C++ Primer读书笔记)

第七章 类

练习7.32  定义你自己的Screen和Window_mgr,其中clear是Window_mgr的成员,是Screen的友元。

由于Window_mgr中含有Screen对象,所以在Window_mgr之前要声明Screen。

因为clear中调用Screen成员,所以Screen要在clear定义之前定义。

因为Screen类中要声明友元函数clear,而clear是Window_mgr的成员函数,所以在Screen之前要定义Window_mgr。

好乱啊啊啊啊

代码:

#include <iostream>
#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;//{Screen(24, 80, ' ')};
};

class Screen {
public:
	typedef std::string::size_type pos;
	Screen() = default;
	Screen(int ht, int wd) : 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 ht, pos wd) const;
	Screen &move(pos r, pos c);
	void some_number() const;
	Screen &set(char);
	Screen &set(pos, pos, char);
    Screen &display(std::ostream &os)
    {
    	do_display(os);
    	return *this;
    }
    const Screen &display(std::ostream &os) const
    {
    	do_display(os);
    	return *this;
    }
    //friend class Window_mgr;
    friend void Window_mgr::clear(ScreenIndex);
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	mutable size_t access_ctr;
	std::string contents;
	void do_display(std::ostream &os) const
	{
		os << contents;
	}
};

inline Screen &Screen::move(pos r, pos c)
{
	pos row = r * width;
	cursor = row + c;
	return *this;
}

char Screen::get(pos r, pos c) const
{
	pos row = r * width;
	return contents[row + c];
}

void Screen::some_number() const
{
	++access_ctr;
}

inline Screen &Screen::set(char c)
{
	contents[cursor] = c;
	return *this;
}

inline Screen& Screen::set(pos r, pos col, char ch)
{
	contents[r * width + col] = ch;
	return *this;
}

void Window_mgr::clear(ScreenIndex i)
{
	Screen &s = screens[i];
	s.contents = std::string(s.height * s.width, ' ');
}

int main()
{
	Screen myscreen(5, 5, 'X');
	myscreen.move(4, 0).set('#').display(std::cout);
	std::cout << '\n';
	myscreen.display(std::cout);
    return 0;
}

  

对于这一句

std::vector<Screen> screens{Screen(24, 80, ' ')};

暂时只能改成

std::vector<Screen> screens;

因为第一个需要调用构造函数,那样的话。。。Screen就要定义在Window_mgr前面。。。。我要疯了。。。。

posted @ 2015-09-30 16:42  我不吃饼干呀  阅读(942)  评论(0编辑  收藏  举报