#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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.