文章目录
什么是this指针
- 不同的对象各自拥有独立的成员变量,但它们共享同一份成员函数代码,那么在成员函数中如何区分所访问的成员变量隶属于哪个对象?
cpp
复制代码
#include <iostream>
using namespace std;
class Student{
public:
Student(int age, const string &name){
m_age = age;
m_name = name;
}
void print(){
cout << m_name << ":" << m_age << endl;
}
private:
int m_age;
string m_name;
};
int main(void){
Student zs(12, "zhangsan");
Student ls = Student(13, "lisi");
zs.print();
ls.print();
return 0;
}
- this是一个用于标识对象自身的隐式指针,代表对象自身的地址
- 在编译类成员函数时,C++编译器会自动将this指针添加到成员函数的参数表中。在用类的成员函数时,调用对象会把自己的地址通过this指针传递给成员函数
- 以上程序编译器编译后的样子,大致如下:
cpp
复制代码
#include <iostream>
using namespace std;
class Student{
public:
Student(Student *this, int age, const string &name){
this->m_age = age;
this->m_name = name;
}
void print(Student *this){
cout << this->m_name << ":" << this->m_age << endl;
}
private:
int m_age;
string m_name;
};
int main(void){
Student zs(12, "zhangsan"); // (&zs, 12, "zhangsan")
Student ls = Student(13, "lisi");
zs.print(); //print(&zs)
ls.print();//print(&ls)
return 0;
}
this指针的应用
- 需要显示使用this指针的常见场景:
- 类中的成员变量和参数变量名字一样,可以通过this指针区分
- 从成员函数中返回调用对象自身(返回自引用),支持链式调用
- 在成员函数中销毁对象自身(对象自销毁)
cpp
复制代码
#include <iostream>
using namespace std;
class Counter{
private:
int count;
public:
Counter(int count = 0){
this->count = count;
}
Counter &add(void){
++count;
return *this;
}
void print(void){
cout << count << endl;
}
void destroy(void){
cout <<"this : " << this << endl;
delete this; //销毁对象本身
}
};
int main(void){
Counter cnt;
cnt.print();
cnt.add().add().add();
cnt.print();
Counter *pcn = new Counter;
pcn->add();
pcn->print();
pcn->destroy();
cout<<"pcn: " <<pcn <<endl;
return 0;
}