<C++>15.this指针

来源:互联网 发布:祛痘产品淘宝 编辑:程序博客网 时间:2024/06/07 00:53

15.this指针

一、概述


1、概念:

this指针是隐含与每一个成员函数中的特殊指针。它指向正操作该成员函数的对象。


2、this指针的产生:

当对象调用成员函数时,程序先将对象的地址赋予this指针,然后调用成员函数。

 

二、应用举例

/* this_ptr.c */#include <iostream>using namespace std;class A{private:int n;public:void set_value(int x){this->n = x;cout<<"this指针指向的地址: "<<this<<endl;}void print_n(){cout<<"对象的n值:"<<n<<endl;}};int main (int argc, char *argv[]){A a;cout<<"a的内存地址:"<<&a<<endl;a.set_value(3);a.print_n();return 0;}


结果:

 

可以看到this指针指向的地址就是调用成员函数的对象的地址,this->n等价于a.n