C++primer第5版课后练习习题答案7.23

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class Screen{
public:
	//friend void clear(Screen & sc);
	friend class Window_mgr;
	typedef string::size_type pos;
	Screen & movCursor(pos row, pos col)
	{
		if (row > width || col > height)
		{
			cerr<< "wrong row or col!" << endl;
			throw EXIT_FAILURE;
		}
		else
		{
			cursor = row * width + col;
			return *this;
		}
	}
	Screen & setCursor(pos row, pos col, char ch)
	{
		content[row * width + col] = ch;
		return *this;
	}
	Screen & setCursor(char ch)
	{
		content[cursor] = ch;
		return *this;
	}
	Screen & display(ostream &os = cout);
	const Screen & display(ostream &os = cout) const;
	char getCursor()
	{
		return content[cursor];
	}
	char getCursor(pos row, pos col)
	{
		return content[row * width + col];
	}
public:
	//Screen()=default;
	Screen(istream & in = cin);   //默认实参是cin  如果在定义default默认构造函数则重复定义 编译器不知道调用哪个构造函数

	//Screen(pos wt,pos ht):width(wt),height(ht){}
	Screen(pos wt,pos ht,char c):width(wt),height(ht),content(wt*ht ,c){}
	Screen(pos wd, pos ht, const string & cstr = "");

private:
	static const char bkground = '0';
private:
	void do_display(ostream & os) const ;
	pos width = 0;
	pos height = 0;
	pos cursor = 0;
	string content = "";
};
Screen::Screen(istream & in )   //默认cin输入  不能重复定义默认实参
	{
		char ch;
		in>>width>>height>>ch;
		content.assign(width*height,ch);
	}

Screen::Screen(pos wd, pos ht, const string & cstr): width(wd), height(ht)
	{
		content.assign(wd * ht, bkground);

		if (cstr.size() != 0)
		{
			content.replace(0, cstr.size(), cstr);
		}
	}
void Screen::do_display(ostream & os ) const
{
	for(pos i=0;i!=height;++i)
		{
			for (pos j=0;j!=width;++j)
			os<<content[i*width+j];
			os<<endl;
		}
}
class Window_mgr{
public:
	typedef vector<Screen>::size_type ScreenIndex;
	void clear(ScreenIndex i);
	ScreenIndex addScreen(const Screen & sc);
private:
	vector<Screen> screens{Screen(24, 80)};

};
Window_mgr::ScreenIndex Window_mgr::addScreen(const Screen &sc)
{
	screens.push_back(sc);
	return screens.size()-1;
}
void Window_mgr::clear(ScreenIndex i)
{
	Screen &s=screens[i];
	s.content=string(s.height*s.width,' ');
}
Screen & Screen::display(ostream & os)
{
	do_display(os);
	return *this;
}
const Screen & Screen::display(ostream & os) const
{
	do_display(os);
	return *this;
}
int main()
{
	//Screen myScreen(5,5);
	cout<<"默认cin参数构造函数调用 输入参数宽高 字符 : wd ht ch "<<endl;
	Screen myScreen; //默认cin参数的构造函数

	myScreen.movCursor(4,0).setCursor('#').display();
	cout<<endl;
	myScreen.display(cout);
	cout<<endl;


	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值