特点
1.实质是一个形参,隐藏在非静态成员函数中形参列表的最左侧。
2.是一个编译器提供的一个本对象的常指针
3.生成时机:本对象在开辟空间时,构造函数前,既有了this指针,所以类中的构造函数也是又this指针的。
4.因为有了本对象的指针,所以类中非静态成员函数是可以调用类中的属性或方法的。要用 -> 来访问成员变量或成员函数。
5.应用场景:1.当成员函数中行参变量名与类中的属性变量名相同时,用于区别。2.返回本对象。
6友元函数没有 this 指针,因为友元不是类的成员。只有成员函数才有 this 指针。
7.this指针是编译器提供给程序员使用的,this指针中本对象是直接放在寄存器上,this并非类中的属性,所以它并不占用类的空间。
this指针的由来(C语言):
#include <stdio.h>
typedef struct Stu
{
char* name;
int age;
void (*pfun)();
}Stu;
void showInfo(Stu*const this)
{
printf("姓名:%s ,年龄:%d \n",this->name,this->age);
}
int main()
{
Stu stu = {"zhangsan",18,showInfo};
stu.pfun(&stu);
return 0;
}
>>姓名:zhangsan ,年龄:18
C++中this指针使用:
#include <iostream>
using namespace std;
class Stu
{
private:
string name;
int age;
public:
//1.当成员函数中行参变量名与类中的属性变量名相同时,用于区别。
Stu(string name, int age)
{
this->name = name;
this->age = age;
}
//2.返回本对象。
Stu& setName(string name)
{
this->name = name;
return *this;
}
void showInfo()
{
cout << "姓名:" << name << ",年龄" << age << endl;
}
};
int main()
{
Stu stu("zhangsan",18);
stu.setName("lisi").showInfo();
return 0;
}
>>姓名:lisi,年龄18