在C++中成员变量和成员函数是分开存储的。每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码。
那么问题是:这一块代码是如何区分是哪个对象调用自己的呢?
C++通过提供特殊的对象指针,this指针,解决上述问题。this指针指向被调用的成员函数所指向的对象。
this指针是隐含在每一个非静态成员函数的一种指针
this指针不需要定义,直接使用即可。
this指针的用途
- 当形参和成员变量同名时,可用this指针来区分
复制代码
1
2
3
4
5
6
7
8class Person{ public: Person(int age){ this->age = age; } int age; };
- 在类的非静态成员函数中返回对象本身,可使用return *this;
复制代码
1
2
3
4
5
6
7
8
9
10
11
12class Person{ public: Person(int age){ this->age = age; } Person& PersonAddAge(Person &p){ this->age += p.age ; return *this; } int age; };
复制代码
1
2
3
4
5
6
7
8
9void test02(){ Person p1(10); Person p2(10); //链式编程 p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1); cout << p2.age << endl; }
最后
以上就是斯文钢笔最近收集整理的关于类和对象——对象特性——this指针的用途的全部内容,更多相关类和对象——对象特性——this指针内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复