The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. 'this' pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
  For a class X, the type of this pointer is ‘X* const’. Also, if a member function of X is declared as const, then the type of this pointer is ‘const X *const’.

  Following are the situations where ‘this’ pointer is used:

  (1)When local variable’s name is same as member’s name

 1 #include<iostream>
2 using namespace std;
3
4 /* local variable is same as a member's name */
5 class Test
6 {
7 private:
8 int x;
9 public:
10 void setX (int x)
11 {
12 // The 'this' pointer is used to retrieve the object's x
13 // hidden by the local variable 'x'
14 this->x = x;
15 }
16 void print()
17 {
18 cout << "x = " << x << endl;
19 }
20 };
21
22 int main()
23 {
24 Test obj;
25 int x = 20;
26 obj.setX(x);
27 obj.print();
28 return 0;
29 }

  Output:

  x = 20
  

  For constructors, initializer list can also be used when parameter name is same as member’s name.

  (2)To return reference to the calling object

1 /* Reference to the calling object can be returned */
2 Test& Test::func ()
3 {
4 // Some processing
5 return *this;
6 }

  When a reference to a local object is returned, the returned reference can be used to chain function calls on a single object.

 1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 private:
7 int x;
8 int y;
9 public:
10 Test(int x = 0, int y = 0)
11 {
12 this->x = x;
13 this->y = y;
14 }
15 Test &setX(int a)
16 {
17 x = a;
18 return *this;
19 }
20 Test &setY(int b)
21 {
22 y = b;
23 return *this;
24 }
25 void print()
26 {
27 cout << "x = " << x << " y = " << y << endl;
28 }
29 };
30
31 int main()
32 {
33 Test obj1(5, 5);
34
35 // Chained function calls. All calls modify the same object
36 // as the same object is returned by reference
37 obj1.setX(10).setY(20);
38
39 obj1.print();
40 return 0;
41 }

  Output:

  x = 10 y = 20

  Exercise:
  Predict the output of following programs. If there are compilation errors, then fix them.

  Question 1

 1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 private:
7 int x;
8 public:
9 Test(int x = 0)
10 {
11 this->x = x;
12 }
13 void change(Test *t)
14 {
15 this = t;
16 }
17 void print()
18 {
19 cout << "x = " << x << endl;
20 }
21 };
22
23 int main()
24 {
25 Test obj(5);
26 Test *ptr = new Test (10);
27 obj.change(ptr);
28 obj.print();
29 return 0;
30 }

  类Test的成员函数change有问题,现修改为:

1 void change(Test *t)
2 {
3 *this = *t;
4 }

  因为this指针为const指针,其本身无法进行修改。修改后的输出内容为:  10

  Question 2

 1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 private:
7 int x;
8 int y;
9 public:
10 Test(int x = 0, int y = 0)
11 {
12 this->x = x;
13 this->y = y;
14 }
15 static void fun1()
16 {
17 cout << "Inside fun1()";
18 }
19 static void fun2()
20 {
21 cout << "Inside fun2()";
22 this->fun1();
23 }
24 };
25
26 int main()
27 {
28 Test obj;
29 obj.fun2();
30 return 0;
31 }

  编译错误:"'fun2' : static member functions do not have 'this' pointers"

  Question 3

 1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 private:
7 int x;
8 int y;
9 public:
10 Test (int x = 0, int y = 0)
11 {
12 this->x = x;
13 this->y = y;
14 }
15 Test setX(int a)
16 {
17 x = a;
18 return *this;
19 }
20 Test setY(int b)
21 {
22 y = b;
23 return *this;
24 }
25 void print()
26 {
27 cout << "x = " << x << " y = " << y << endl;
28 }
29 };
30
31 int main()
32 {
33 Test obj1;
34 obj1.setX(10).setY(20);
35 obj1.print();
36 return 0;
37 }

  Output:  x = 10  y = 0

  When we do not return an object by reference, a temporary object is created (which contains copy of the original object)and returned. In question 3, setX() modifies obj1, but returns a different object because return by value is used. So setY() modifies the temporary object.

  Question 4

 1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 private:
7 int x;
8 int y;
9 public:
10 Test(int x = 0, int y = 0)
11 {
12 this->x = x;
13 this->y = y;
14 }
15 void setX(int a)
16 {
17 x = a;
18 }
19 void setY(int b)
20 {
21 y = b;
22 }
23 void destroy()
24 {
25 delete this;
26 }
27 void print()
28 {
29 cout << "x = " << x << " y = " << y << endl;
30 }
31 };
32
33 int main()
34 {
35 Test obj;
36 obj.destroy();
37 obj.print();
38 return 0;
39 }

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
  

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  09:26:31

  

'this' pointer in C++的更多相关文章

  1. 苹果手机不支持click文字 需要添加 cursor:pointer 才能 识别可以点击

    给一个div 绑定一个 click事件,  苹果手机会识别不了,必须添加一个 cursor:pointer 才能 识别可以点击.安卓正常识别.

  2. [LeetCode] Copy List with Random Pointer 拷贝带有随机指针的链表

    A linked list is given such that each node contains an additional random pointer which could point t ...

  3. Pointer's NULL And 0

    问题起源 在使用Qt框架的时候, 经常发现一些构造函数 *parent = 0 这样的代码. 时间长了, 就觉的疑惑了. 一个指针不是等于NULL吗? 这样写, 行得通吗? 自己测试一下就可以了. 测 ...

  4. C++中Reference与Pointer的不同

    Reference与Pointer中直接存储的都是变量的地址, 它们唯一的不同是前者的存储的地址值是只读的, 而后者可以修改. 也就是说Reference不支持以下操作: *a = b 其他语言, 如 ...

  5. LeetCode——Copy List with Random Pointer(带random引用的单链表深拷贝)

    问题: A linked list is given such that each node contains an additional random pointer which could poi ...

  6. Leetcode Copy List with Random Pointer

    A linked list is given such that each node contains an additional random pointer which could point t ...

  7. 移动端/H5关于cursor:pointer导致的问题

    cursor属性规定要显示的光标的类型(形状),该属性定义了鼠标指针放在一个元素边界范围内时所用的光标形状(不过 CSS2.1 没有定义由哪个边界确定这个范围). 不过,这个属性用在PC端没有任何问题 ...

  8. 关于编译报错“dereferencing pointer to incomplete type...

    今天同事问了我一个问题,他make的时候报错,“第201行:dereferencing pointer to incomplete type”,我随即查阅了很多资料,也没看出个所以然.最后问题得到了解 ...

  9. pointer to function

    指针.函数.数字.结构体.指针函数.函数指针 初学不好区分,做点儿实验来有效区分一下,以下代码采用dev-C++平台测试 //pointer to fucntion 函数功能是 基地址加偏移量得到偏移 ...

  10. TObject、Pointer、Interface的转换

    unit Unit4; ));   ));   ));   //将Obj转为接口   //LInf1 := ITest(Pointer(LObj1));       //无法转换了,丢失了接口信息   ...

随机推荐

  1. 【python】使用python十分钟创建个人聊天机器人教程

    以青云客和图灵机器人接口示范python创建个人聊天机器人教程 一.以青云客聊天机器人为例示范get请求 官方网址:http://api.qingyunke.com/ 1.接入指引 请求地址 http ...

  2. Java测试开发--Java基础知识(二)

    一.java中8大基本类型 数值类型:byte.short.int .float.double .long 字符类型:char 布尔类型:boolean 二. 封装:将属性私有化,不允许外部数据直接访 ...

  3. Java日期API

    JDK8之前日期时间API java.util.Date类 表示特定的瞬间,精确到毫秒 构造器: Date():使用无参构造器创建的对象可以获取本地当前时间. Date(long date) 常用方法 ...

  4. [啃书] 第3篇 - 结构体及其操作/浮点数&圆周率/复杂度/测试

    啃书部分已单独做成Gitbook了,后续不再更新.详情访问个人网站ccoding.cn或ccbyte.github.io 前言 本篇总结自<算法笔记>2.8-2.10 正文 知识点1:结构 ...

  5. Java学习(二十二)

    学了一个在css中叫font的样式: 感觉还是挺好用的 不过要注意如果把font放在最后,其他会使用默认值,可能会覆盖掉前面的 例如新学的行高 在font中语法是 font:30px/40px &qu ...

  6. html+css第一篇

    行间样式表 <div style="--"></div> 内部样式表 <style>----</style> 外部样式表 <l ...

  7. CF1264D2 Beautiful Bracket Sequence (hard version)

    考虑\(D1\)的\(O(n^2)\),我们直接进行组合处理. 考虑在\(p\)这个位置,左边有\(l\)个(,右边有\(r\)个),左边有\(l\)个问号,右边有\(r\)个问号. 这个位置的贡献为 ...

  8. Atcoder Grand Contest 001 F - Wide Swap(拓扑排序)

    Atcoder 题面传送门 & 洛谷题面传送门 咦?鸽子 tzc 来补题解了?奇迹奇迹( 首先考虑什么样的排列可以得到.我们考虑 \(p\) 的逆排列 \(q\),那么每次操作的过程从逆排列的 ...

  9. Atcoder Grand Contest 003 F - Fraction of Fractal(矩阵乘法)

    Atcoder 题面传送门 & 洛谷题面传送门 Yet another AGC F,然鹅这次就没能自己想出来了-- 首先需注意到题目中有一个条件叫做"黑格子组成的连通块是四联通的&q ...

  10. Redis键空间通知(keyspace notification),事件订阅

      Redis键空间通知(keyspace notification),事件订阅   应用场景:有效期优惠券.24小时内支付.下单有效事件等等. 功能概览 键空间通知使得客户端可以通过订阅频道或模式, ...