C++中的this指针究竟是什么?

      先来看一个简单的程序:

 

#include <iostream>
using namespace std;

class Human
{
private:
	int age;

public:
	void setAge(int a)
	{
		age = a;
	}

	int getAge()
	{
		return age;
	}
};

int main()
{
	Human h;
	h.setAge(10);
	cout << h.getAge() << endl; // 10

	return 0;
}

     稍微改动上述程序,得到:

 

 

#include <iostream>
using namespace std;

class Human
{
private:
	int age;

public:
	void setAge(int age)
	{
		age = age; // 真正的字段age被形参age屏蔽
	}

	int getAge()
	{
		return age;
	}
};

int main()
{
	Human h;
	h.setAge(10);
	cout << h.getAge() << endl; // -858993460

	return 0;
}

      那怎么办呢?用this指针吧:

#include <iostream>
using namespace std;

class Human
{
private:
	int age;

public:
	void setAge(int age)
	{
		this->age = age;
	}

	int getAge()
	{
		return age;
	}
};

int main()
{
	Human h;
	h.setAge(10);
	cout << h.getAge() << endl; // 10

	return 0;
}

     实际上,在编译器看来,成员函数setAge是这样的:void setAge(Human *const this, int age); 也就是说this指针是编译器默认的成员函数的一个参数,在调用h.setAge(10);时,在编译看来,实际上是调用了Human::setAge(&h, 10); 这样,就实现了对象与其对应的属性或方法的绑定。下面这个程序之所以能区分不同不同对象,也完全是拜this指针所赐。

 

 

#include <iostream>
using namespace std;

class Human
{
private:
	int age;

public:
	void setAge(int a)
	{
		age = a;
	}

	int getAge()
	{
		return age;
	}
};

int main()
{
	Human h1, h2;
	h1.setAge(10);
	cout << h1.getAge() << endl; // 10

	h2.setAge(20);
	cout << h2.getAge() << endl; // 20

	return 0;
}

     接着来欣赏如下程序:

 

 

#include <iostream>
using namespace std;

class Human
{
private:
	int age;

public:
	void setAge(int a)
	{
		cout << this << endl;  // 0012FF7C
		age = a;
		cout << age << endl;   // 10
	}

	int getAge()
	{
		return age;
	}
};

int main()
{
	Human h;
	cout << &h << endl;         // 0012FF7C
	h.setAge(10);
	cout << h.getAge() << endl; // 10

	return 0;
}

     this指针是指向对象的,而静态成员函数并不属于某个对象,因此,在静态成员函数中,并没有this指针,这一点值得注意。
 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值