this指针
来源:互联网 发布:什么软件可以录音 编辑:程序博客网 时间:2024/06/05 19:03
一:概念
this指针本质上就是一个指针,对于成员函数来讲,this指针指向调用对象的地址,对于构造函数来讲,this指针指向正在构造的对象的地址。
二:作用:
1:this指针可以用于在构造函数中区分与形参名相同的成员变量;
代码实例:
#include<iostream>using namespace std;#include<string>class StuInfo{private:string m_name;int m_age;public:StuInfo(const string& m_name, int m_age){//m_name = m_name; 这样写就是错误的,前面的m_name实际上是形参,而不是类的成员变量//因为当两个变量同名时,局部优先//m_age = m_age;this->m_name = m_name;this->m_age = m_age;}void show(){cout << "my name is " << m_name << "," << m_age << " years old!" << endl;}};int main(){StuInfo s("Dick", 25);s.show();return 0;}
2:this指针可以用于返回自引用的场合;
代码实例:
#include<iostream>using namespace std;class Counter{private:int m_data;public:Counter():m_data(0){}Counter& add(){m_data++;return *this;}Counter& dec(){m_data--;return *this;}void show(){cout << m_data << endl;}};int main(){Counter c;c.add().add().add().dec().show();//结果为2c.show();//如果把函数add,dec的返回值去掉引用,结果将变为1,这是因为如果是返回的引用值 //就一直是对那个对象本身进行操作,而去掉引用则是对副本进行操作,真正对于对象c而言,值操作了一次return 0;}
3:this指针可以作为函数的参数,实现对象间的交互;
代码实例:
#include<iostream>using namespace std;#include<string>class Student;//必须向前声明,因为类Teacher中要用到类Studentclass Teacher{private:string m_answer;public:void educate(Student* ps);//只能声明函数而不能定义函数,是因为前面只是声明了类Student,但是 //并不知道类Student中具体的东西,这样就必须等到定义类Student之后,才定义这个函数void replay(const string& answer){m_answer = answer;}};class Student{public:void ask(const string& question, Teacher* pt){cout << question << endl;pt->replay("this is ....");}};void Teacher::educate(Student* ps){ps->ask("what is this ?", this);cout << m_answer << endl;}int main(){Teacher t;Student s;t.educate(&s);return 0;}
0 0
- this指针
- this指针
- this指针
- this指针
- this指针
- this 指针
- this指针
- this指针----
- this指针
- this 指针
- This 指针
- this指针
- This指针
- this指针
- this指针
- this 指针
- this指针
- this指针
- 剑指Offer之 - 树的镜像
- Linux下检查硬盘是否为固态硬盘
- HealthKit开发教程之HealthKit的辅助数据
- 算法笔试面试题_商场搞活动,满100减30,满200减80,问1000元最多能买多少钱的东西?
- 根据字符串宽度算高度
- this指针
- dump文件的创建及使用
- 去掉flash builder生成apk时候自动加air前缀的方法
- Apache lucene solr
- HTTP协议头解析
- 7天学会MVC——第1天
- 仿微信朋友圈动态列表
- java新手系列 -- 调试程序
- java上传文件以流方式判断类型