c++ 返回*this的成员函数

*this返回的是调用本函数的对象的引用,返回的是函数本身,而非对象的副本。 

在const成员函数中返回*this,返回的是一个常量引用,无法对对象的成员再做改变。

class Screen {
public:
	//pos
	typedef string::size_type pos;
	//构造函数
	//1默认构造函数
	Screen() = default;
	//接受高、宽、字符三个量来创建窗口。
	Screen(pos ht, pos wd, char c) :height(ht),width(wd),
	contents(ht*wd,c){}
	//接受高、宽两个参数来创建空白窗口
	Screen(pos ht, pos wd) :height(ht), width(wd),
	contents(ht*wd,' ') {}
	Screen& set(char);
	Screen& set(pos, pos, char);
	char get() const
	{
		return contents[cursor];
	}
	inline char get(pos ht, pos wd) const;
	Screen& move(pos r, pos c);
	Screen& display(ostream &os) {
	
		do_display(os); return *this;
	}
	const Screen& display(ostream& os) const {
		do_display(os); return *this;
	}
	
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	string contents;
	void do_display(ostream& os) const { for (pos i = 0; i < width * height; ++i) {
		if (i % width == 0) cout << endl;
		cout << contents[i];
		
	} }
};
inline
Screen& Screen::move(pos r, pos c) {
	pos row = r * width;
	cursor = row + c;
	return *this;
}
char Screen::get(pos r, pos c) const {

	pos row = r * width;
	return contents[row + c];
}

class Window_mgr {
private:
	vector<Screen> screens{ Screen(24,80,'a') };

};
inline Screen& Screen::set(char c) {
	contents[cursor] = c;
	return *this;
}
inline Screen& Screen::set(pos r, pos col, char ch) {

	contents[r * width + col] = ch;
	return *this;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖豆人鄭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值