C++ 最常见的显示使用this 指针场景

有一种场景必须显示使用this指针,需要将一个对象整体引用而不是引用对象的一个成员时。最常见的情况是在成员函数中使用this,返回对调用该函数的对象的引用。


#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <list>
#include <string>


class Screen
{
public:
	typedef std::string::size_type index;

	Screen();

	//constructor
	Screen(index h, index w, std::string cont) :height(h), width(w), contents(cont) {}

	//get char where cursor points to
	char get() const { return contents[cursor]; }
	//get char where column and row points to
	char get(index ht, index wd)  const;

	// get cursor
	index get_cursor()  const { return cursor; }

	// set content where cursor points to
	Screen& set(char);
	//set content where column and row points to
	Screen& set(index, index, char);

	//move cursor to where column and row points to
	Screen& move(index, index);

	//show contents
	const Screen& display(std::ostream& os) const;

private:
	std::string contents;
	index  cursor;
	index  height;
	index  width;



};


Screen::Screen()
{

}




char Screen::get(index ht, index wd) const
{
	index row = wd*width;
	return contents[row + ht];
}

Screen& Screen::set(char c)
{
	contents[cursor] = c;
	return *this;
}

Screen& Screen::set(index r, index col, char  c)
{
	index row = r *width;
	contents[row + col] = c;
	return *this;
}

Screen& Screen::move(index r, index c)
{
	index row = r*width;
	cursor = row + c;
	return *this;
}

const Screen& Screen::display(std::ostream& os) const
{
	os << contents;
	return *this;
}




int main(int argc, char* argv[])
{
	Screen myScreen(5,2,"helloworld");

	myScreen.move(4, 0).set('#').display(std::cout);

	
	
	return 0;
}



如上面代码,成员函数返回对象的引用,可以实现一系列操作在一个表达式中完成,非常cool:

<pre name="code" class="cpp">myScreen.move(4, 0).set('#').display(std::cout);


 

PS .  为什么使用return *this 只能返回使用该成员函数的对象的引用,而不是直接返类型对象?

答:  类定义体结束前,该类型是不完全类型,只能使用该类型的指针或引用 

====================================

另外一种会显式使用this 指针的场景是:  成员函数形参变量与成员变量同名,在成员函数函数体中为了使用成员函数,则必须显式使用this 指针:

class test
{
     int num;
     void  fuck(int);
}

void   test::fuck(int num)
{
   int shit = <span style="color:#ff0000;">num</span> + <span style="color:#ff0000;">this->num</span>;
}

如上,第一个num 使用的是形参,this->num 则使用的是成员变量


  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值