屏幕Screen类文件编写
生活随笔
收集整理的這篇文章主要介紹了
屏幕Screen类文件编写
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
注意:
inline 定義的函數(shù)必須放在 .h 文件中,否則編譯器報錯!
其次,注意寫全稱在 .h 里,如 std::
screen.h 頭文件
#ifndef SCREEN_H #define SCREEN_H #include<string> #include<iostream>class Screen { public:typedef std::string::size_type index; //定義序號別名Screen(index hgth, index wdth, const std::string &cntnts); //聲明構造函數(shù)char get() const { return contents[cursor];} //定義成員函數(shù) get() 返回位置處的字符char get(index ht, index wd) const; //聲明成員函數(shù) get(a,b) get重載函數(shù)index get_cursor() const; //聲明成員函數(shù) get_cursor() 返回indexScreen& move(index r, index c); //聲明成員函數(shù) move(a,b) 返回screen類引用Screen& set(char); //聲明成員函數(shù) set(a) 返回screen類引用Screen& display(std::ostream &os); //聲明成員函數(shù) display(輸出流) 返回screen類引用//----------------- 注意寫 std:: ------------------------------------------------------ private:std::string contents; //定義成員變量 內(nèi)容字符串index cursor; //定義成員變量 光標序號index height, width; //定義成員變量 高,寬 }; #endifscreen.cpp 頭文件具體實現(xiàn)文件
#include"screen.h" #include<iostream> #include<string> using namespace std;Screen::Screen(index hgth, index wdth, const string &cntnts = " "):cursor(0), height(hgth),width(wdth) { //定義構造函數(shù) 光標位置為0,屏幕尺寸初始化contents.assign(hgth*wdth, ' '); //填充文本初始化為hgth*wdth個 空格if(!cntnts.empty())contents.replace(0,cntnts.size(),cntnts); //從第0位開始,用輸入的字符串替換掉 }char Screen::get(index r, index c) const //定義成員函數(shù) get(a,b) {if(!contents.empty() && r > 0 && c > 0 && r <= height && c <= width){return contents[(r-1) * width + c - 1]; //返回(r,c)行列處的字符}else{cout << "超出屏幕范圍!!!" << endl;}return '!'; }Screen::index Screen::get_cursor() const //定義成員函數(shù)get_cursor() {return cursor; //注意返回值類型前加類名! }Screen& Screen::move(index r, index c) //定義成員函數(shù) move(),光標cursor移動到指定位置 {index row = r * width;cursor = row + c;return *this; }Screen& Screen::set(char c) //定義成員函數(shù) set(a) {contents[cursor] = c; //光標處字符=creturn *this; }Screen& Screen::display(ostream &os) //定義成員函數(shù) display() {string::size_type index = 0;while(index != contents.size()) //把字符按每行寬度個輸出{os << contents[index];if((index+1)%width == 0){os << '\n';}++index;}return *this; }main_screen.cpp 主函數(shù)
#include"screen.h" #include<iostream> using namespace std; int main() {Screen myscreen(5,6,"aaaaa\naaaaa\naaaaa\naaaaa\naaaaa\n");//定義Screen類對象myscreen,初始化為5行6列的字符myscreen.move(4,0).set('#').display(cout);//move使光標移動到指定的第5行,第1列,返回的是對象自己*this//set使光標處字符變成#//display用cout輸出所有字符cout << "光標當前所在位置和字符為: " << myscreen.get_cursor() << " " << myscreen.get() << endl;string::size_type r=1, c=1;cout << "輸入你要獲取的位置行列數(shù)字(從1開始):" << endl;cin >> r >> c;cout << myscreen.get(r,c) << endl;return 0; }運行結果
總結
以上是生活随笔為你收集整理的屏幕Screen类文件编写的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 22. 括号生成(回溯
- 下一篇: horizon流程图_项目实施流程和规范