#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;
}
C++primer第5版课后练习习题答案7.23
最新推荐文章于 2016-10-31 11:16:04 发布