參考來源:c++primer
//Screen.h;
#include <iostream>
#include <string>
using namespace std;
class Screen {//表示顯示器中的一個窗口;
private:
unsigned height = 0, width = 0;//屏幕的長和寬;
unsigned cursor = 0;//光標(biāo)的當(dāng)前位置;
string contents;//屏幕的內(nèi)容;
public:
Screen() = default;//默認(rèn)構(gòu)造函數(shù);
Screen(unsigned ht, unsigned wt) : height(ht), width(wt), contents(ht * wt, ' ') {}//接受長和寬, 將contents初始化成給定的空白;
Screen(unsigned ht, unsigned wt, char c) : height(ht), width(wt), contents(ht * wt, c) {}//接受長和寬以及一個字符, 該字符作為初始化之后屏幕的內(nèi)容;
public:
Screen &move(unsigned r, unsigned c) {//返回的是引用, 返回引用的函數(shù)是左值的,意味著這些函數(shù)返回的是對象本身;函數(shù)的返回值如果不是引用, 則表明函數(shù)返回的是對象的副本;//move : 移動光標(biāo);
cursor = r * width + c;
return *this;
}
Screen &set(char ch) {//將該位置修改為ch;
contents[cursor] = ch;
return *this;
}
Screen &set(unsigned r, unsigned c, char ch) {//函數(shù)重載;
contents[r * width + c] = ch;
return *this;
}
Screen &display() {//輸出contents;
cout << contents;
return *this;
}
};
//Screen.cpp;
#include <iostream>
#include <string>
#include "Screen.h"
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
Screen myScreen(5, 5, 'X');//創(chuàng)建一個Screen對象且初始化;
myScreen.move(4, 0).set('#').display();//所有的這些操作將在同一個對象上執(zhí)行;
cout << endl;
myScreen.display();
cout << endl;
return 0;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者