1. this指针的由来
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210128103727527.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1YWlkZXJ6aHUxMzE0,size_16,color_FFFFFF,t_70)
- 对面蓝色话的补充解释:
- 对象是栈区的(或者堆区), 成员函数是代码段的,栈区的对象可以调用代码段成员函数。
- 构造函数中的this指针指向正在创建的对象
- 普通成员函数中,this指向指向该函数的调用对象
1.1 代码示例
#include <iostream>
using namespace std;
class User{
public:
User(const string& name, int age):m_name(name), m_age(age){
cout << "this:" << this << endl;
}
void who(void){
cout << this->m_name << "," << this->m_age << endl;
}
private:
string m_name;
int m_age;
};
int main(void){
User u1("xuehui", 1);
cout << "&u1:" << &u1 << endl;
User u2("xuehui", 2);
cout << "&u2:" <<&u2 << endl;
u1.who();
u2.who();
return 0;
}
this:0x7fff58d75340
&u1:0x7fff58d75340
this:0x7fff58d75370
&u2:0x7fff58d75370
xuehui,1
xuehui,2
2. 什么是this指针
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210128113130202.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1YWlkZXJ6aHUxMzE0,size_16,color_FFFFFF,t_70)
3. this指针应用
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210128113310151.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1YWlkZXJ6aHUxMzE0,size_16,color_FFFFFF,t_70)
3.1 需要显示使用this指针的场景
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210128113401372.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1YWlkZXJ6aHUxMzE0,size_16,color_FFFFFF,t_70)
3.1.1 从成员函数中返回调用对象自身
#include <iostream>
using namespace std;
class Counter{
public:
Counter(int count = 0):m_count(count){}
Counter& add(void){
m_count++;
return *this;
}
int m_count;
};
int main(void){
Counter a;
a.add().add().add();
cout << a.m_count << endl;
}
$ ./a.out
3
3.1.2 从成员函数中销毁对象自身
#include <iostream>
using namespace std;
class Counter{
public:
Counter(int count = 0):m_count(count){}
Counter& add(void){
m_count++;
return *this;
}
Counter destroy(void){
delete(this);
}
int m_count;
};
int main(void){
Counter *a = new Counter;
a->destroy();
cout << a->m_count << endl;
}
3.1.3 this作为函数实参,实现对象间交互
- 把一个成员函数的结果传递给另外一个对象,可以用this。这样做会让代码形成高耦合(代码之间的交互很多,逻辑变得复杂),这样不好。