• C++系列--this指针的用途


    this指针的本质

    • this指针本身是一个成员函数的形参,相当于Python中的self。在调用成员函数时将对象的地址作为实参传递给 this。
    • this形参是隐式的,它并不出现在代码中,而是在编译阶段由编译器默默地将它添加到参数列表中。
    • this 作为隐式形参,本质上是成员函数的局部变量,所以只能用在成员函数的内部,并且只有在通过对象调用成员函数时才给 this 赋值。

    this指针的用途

    • this指针是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。
    • 只有在对象创建后,this指针才有意义。
    • this指针不需要定义,直接使用即可。但只能在类内的非静态成员函数中使用(静态的成员并不属于对象,不和对象关联)。
    • 当形参和成员变量同名时,可以使用this指针进行区分。
    • 当想返回对象本身时,可以用*this返回。

    this指针区分成员变量和形参

    • 当成员变量和形参同名时,为了区分二者,要么使用不同的名称,要么对成员变量使用this指针进行区分。
    • 可以将成员变量命名为m_age, m: member的缩写。
    code:
    	#include
    	using namespace std;
    	class Person
    	{
    	public:
    		int age = 18;				// this->age = 18
    		Person(int age)
    		{
    			// age = age; 			// 无法给成员变量初始化为形参的age,这里的age编译器自动认为是Person(int age)中的age
    			this->age = age;		// this指针指向的是被调用的成员函数所属的对象
    		}
    	
    	};
    	void main()
    	{
    		Person p1(22);
    		cout << p1.age << endl;
    		system("pause");
    	};
    result:
    	22
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    this作为成员函数返回值

    • 假设成员变量要实现不断地自加,可以使用链式编程思想,可以不断追加。
    • 当返回对象本身,并且以引用方式返回时,就是一直对该对象进行操作。
    code:
    	#include
    	using namespace std;
    	class Person
    	{
    	public:
    		int m_age = 18;
    		Person(int age)
    		{
    			m_age = age;
    		}
    		Person& age_plus(Person p1)
    		{
    			m_age += p1.m_age;		// this指针指向的是被调用的成员函数所属的对象
    			return *this;
    		}
    		Person age_plus_1(Person p1)
    		{
    			m_age += p1.m_age;		// this指针指向的是被调用的成员函数所属的对象
    			return *this;
    		}
    	};
    	void main()
    	{
    		Person p1(100);
    		Person p2(p1);
    		Person p3(p1);
    		cout << p2.m_age << endl;
    		p2.age_plus(p1).age_plus(p1).age_plus(p1);			
    		cout << p2.m_age << endl;
    		p3.age_plus_1(p1).age_plus_1(p1).age_plus_1(p1);	// p3.age_plus_1(p1)返回的并不是p3本身,而是一个备份,所以后面两个改变的并不是p3的内容
    		cout << p3.m_age << endl;
    		system("pause");
    	};
    result:
    	100
    	400
    	200
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
  • 相关阅读:
    Visual Studio v1.67改进了深色主题
    固定资产模块事务代码
    Java2EE基础练习_chapter03数组
    数据库的简介
    【论文学习】变分推导
    Java开发常用服务端口整理
    acwing 795前缀和
    什么是内存泄漏?JavaScript 垃圾回收机制原理及方式有哪些?哪些操作会造成内存泄漏?
    开发小程序遇到的问题
    如何修复“AI的原罪”
  • 原文地址:https://blog.csdn.net/weixin_48668114/article/details/132646937