C++中的*this指针

参考链接:https://blog.csdn.net/jx232515/article/details/52759127

1、每个类中都隐含了this指针成员,不用定义;

2、对于定义的每个对象,this指向当前对象的地址;

3、通过对象调用成员函数时,隐含的都要传递this指针作为实参;

4、this指针是常量指针,不能指向别的对象;

5、在成员函数中访问成员数据或其他函数,可以通过this->进行限定,但是通常也是可以省略的。

参考例子:

#include <iostream>
using namespace  std;

//定义一个类
class A
{
public:
	int get()const {return i;} //获取当前数据
	void set(int x)
	{
		this->i = x;
		cout <<"this变量保存的内存地址:\t"<<this<<endl;
	}
private:
	int i;
};

int main()
{
	A a;
	a.set(9);
	cout <<"对象a的内存地址:\t"<<&a<<endl;
	cout << a.get()<<endl;

	A b;
	b.set(999);
	cout <<"对象b的内存地址:\t"<<&b<<endl;
	cout << b.get()<<endl;


	return 0;


}

输出结果:

猜你喜欢

转载自blog.csdn.net/haoaoweitt/article/details/81196441