this指针简介
this指针是一个隐含参数,用来指向 成员函数所属类 定义的对象,this指针 会根据当前对象变化而变化。
this指针的特性
<1>this指针 类型为 类类型*const 。
例如: sudent * const
<2>this 指针不是对象本身的一部分,故不影响sizeof()的大小,
<3>this指针的作用于 在类成员函数中
<4>this指针是类成员函数的一个默认隐含参数,由系统自动维护。
例如:
class student
{
public:
void InitStudent(char *name, char * gender, int age)
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
}
void PirntStudent()
{
cout <<_name<< _gender << _age << endl;
}
private:
char _name[20];
char _gender[5];
int _age;
};
这个类在被编译器编译的时候经过一下几个步骤
1.识别类名
2.编译数据成员
3.对函数进行重写 也就是加上this指针
成员函数 InitStudent()变为
void InitStudent(student *const this, char *name, char *gender, int age)
{
strcpy(this->_name, name);
strcpy(this->_gender, gender);
this->_age = age;
}
主函数
int main()
{
student s1,s2,s3;
s1.InitStudent("张三 ", "男 ", 18);
s1. PirntStudent();
s2.InitStudent("李四 ", "男 ", 10);
s2.PirntStudent();
s3.InitStudent("幺妹 ", "女 ", 17);
s3.PirntStudent();
return 0;
}