C++ this指针注意事项

this使用注意点

一种情况就是,在类的非静态成员函数中返回类对象本身的时候,直接使用 return *this;另外一种情况是当参数与成员变量名相同时,如this->n = n (不能写成n = n)。

this只能在成员函数中使用。

全局函数、静态函数都不能使用this.
实际上,成员函数默认第一个参数为T * const this。
例如:

class A
 {
  public:
     int fun(int p)
     {
     }
 };

其中,fun的原型在编译器看来应该是:

int fun(A * const this,int p);

当调用一个类的成员函数时,编译器将类的指针作为函数的this参数传递进去。如:

A a;
a.fun(10);

此处,编译器将会编译成:

A::fun(&a,10);

应用场景

有一种显示必须要使用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;
}

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

class test
{
     int num;
     void  func(int);
}
 
void   test::func(int num)
{
   int num_add = num + this->num;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值