this指针的认识
1.什么是this指针
首先来看下面这段代码,从下面的代码中来引伸出什么是this指针
class Student {
private:
char _name[10];
char _sex[10];
int _age;
public:
void InitStudent(const char name[], const char sex[], int age) {
strcpy(_name, name);
strcpy(_sex, sex);
_age = age;
}
void PrintStudent()
{
cout << _name << "-" << _sex << "-" << _age << endl;
}
void SetAge(int age) {
_age = age;
}
};
int main()
{
Student s1, s2;
s1.InitStudent("lily", "男", 12);
s2.InitStudent("mary", "男", 16);
s1.PrintStudent();
s2.PrintStudent();
cout << sizeof(s1) << endl;
cout << sizeof(Student) << endl;
system("pause");
return 0;
}
Student类中有InitStudent与PrintStudent两个成员函数,函数体中没有关于不同对象的区分,那当s1调用InitStudent函数时,该函数是如何知道应该设置s1对象,而不是设置s2对象呢?
原因就在于C++编译器给每个“非静态的成员函数“增加了一个隐藏的指针参数,让该指针指向当前对象(该指针即为隐藏的this指针),函数体中所有成员变量的操作都是通过该指针去访问。不需要用户来传递,编译器自动完成。
那么就有人问了,隐藏的this指针位置在哪呢?看下面这段c代码
struct Student
{
char _name[20];
char _gender[3];
int _age;
};
void InitStudent(Student* ps, char* name, char* gender, int age) {
strcpy(ps->_name, name);
strcpy(ps->_gender, gender);
ps->_age = age;
}
void PrintStudent(Student* ps) {
printf("%s\n", ps->_name);
printf("%s\n", ps->_gender);
printf("%d\n", ps->_age);
}
int main()
{
struct Student s1, s2;
InitStudent(&s1, "lily", "男", 12);
InitStudent(&s2, "mary", "男", 16);
PrintStudent(&s1);
PrintStudent(&s2);
system("pause");
return 0;
}
此处的指针ps就相当于this指针,只不过在c++中是使用隐藏this指针
2.this指针的特性
1.this指针的类型为类类型
2.this指针的使用只能是"成员函数"的内部
3.this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针。
4.this指针是成员函数第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递
注意:this指针主要是通过ecx寄存器传递,但并不是所有都通过this指针来传递
3.this指针的使用注意事项
1.在使用this指针时,常出现的问题就是this指针可以为空吗?
结论:
(1)当以对象.成员函数()时,this指针不会为空
(2)当以p->成员函数()时,最终是将p最为参数传递给该成员函数,如果p指向的是nullptr,那么this指针就是nullptr
演示一下结论(2)
class A
{
public:
void PrintA()
{
cout << _a << endl;
}
void Show()
{
cout << "Show()" << endl;
}
private:
int _a;
};
int main()
{
A* p = NULL;
p->PrintA();
p->Show();
}
2.如果this指针为NULL,成员函数能否正常调用?
结论:
(1).如果在成员函数中没有访问成员变量或者调用成员函数,不会崩溃
(2).如果在成员函数中访问成员变量或者调用成员函数,会崩溃
(成员函数中有成员变量)