c++ this指针

来源:互联网 发布:keilc51中文版软件 编辑:程序博客网 时间:2024/06/03 05:43

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;}

每次调用 s1.InitStudent(“张三 “, “男 “, 18);

this指针的值会被赋值为类对象 S1的地址。因此找到s1对象的数据。以此类推s2,s3 this指针会被赋值为相应的对象地址。

this指针传递的方式有两种:寄存器传递(参数一定的情况),参数压栈(不定参数的情况)这时候用到 _thiscall函数调用约定 从右到左传递参数。

0 0