c++ this指针

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函数调用约定 从右到左传递参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值