c++ 类与对象练习程序2 函数返回

参考来源:c++primer

//Screen.h;
#include 
#include 
using namespace std;

class Screen {//表示显示器中的一个窗口;
    private:
        unsigned height = 0, width = 0;//屏幕的长和宽;
        unsigned cursor = 0;//光标的当前位置;
        string contents;//屏幕的内容;
    public:
        Screen() = default;//默认构造函数;
        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) {}//接受长和宽以及一个字符, 该字符作为初始化之后屏幕的内容;
    public:
        Screen &move(unsigned r, unsigned c) {//返回的是引用, 返回引用的函数是左值的,意味着这些函数返回的是对象本身;函数的返回值如果不是引用, 则表明函数返回的是对象的副本;//move : 移动光标; 
            cursor = r * width + c;
            return *this;
        }
        Screen &set(char ch) {//将该位置修改为ch;
            contents[cursor] = ch;
            return *this;
        }
        Screen &set(unsigned r, unsigned c, char ch) {//函数重载;
            contents[r * width + c] = ch;
            return *this;
        }
        Screen &display() {//输出contents;
            cout << contents;
            return *this;
        }
};
//Screen.cpp;
#include 
#include 
#include "Screen.h"
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    Screen myScreen(5, 5, 'X');//创建一个Screen对象且初始化;
    myScreen.move(4, 0).set('#').display();//所有的这些操作将在同一个对象上执行;
    cout << endl;
    myScreen.display();
    cout << endl;
    return 0;
}

你可能感兴趣的:(c++ 类与对象练习程序2 函数返回)