C++ this指针的用法

this指针的含义及其用法:
1.  this指针是一个隐含于每一个成员函数中的特殊指针。
    它指向正在被该成员函数操作的那个对象。
2.  当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,
    然后调用成员函数,每次成员函数存取数据成员时,由隐含使用this指针。
3.  当一个成员函数被调用时,自动向它传递一个隐含的参数,
    该参数是一个指向这个成员函数所在的对象的指针。
4.  在C++中,this指针被隐含地声明为: X *const this,这意味着不能给this 指针赋值;
    在X类的const成员函数中,this指针的类型为:const X* const,
    这说明this指针所指向的这种对象是不可修改的(即不能对这种对象的数据成员进行   赋值操作);
5.  由于this并不是一个常规变量,所以,不能取得this的地址。
6.  在以下场景中,经常需要显式引用this指针
    (1) 为实现对象的链式引用(如例Person);
    (2) 为避免对同一对象进行赋值操作(如例Location);

(3) 在实现一些数据结构时,如list.

The keyword this identifies a special type of pointer. Suppose that you create an object namedx of class A, and class A has a nonstatic member function f(). If you call the functionx.f(), the keyword this in the body of f() storesthe address of x. You cannot declare the this pointeror make assignments to it.

A static member function does not have a this pointer.

The type of the this pointer for a member function of a classtypeX, is X* const. If the member function is declared with theconst qualifier, the type of the this pointer for that member function for classX, is constX* const.

A const this pointer can by used only with const member functions. Data members of the class will be constant within that function.

The this pointer is passed as a hidden argument to all nonstaticmember function calls and is available as a local variable within the bodyof all nonstatic functions.

For example, you can refer to the particular class object that a memberfunction is called for by using thethis pointer in the body ofthe member function. The following code example produces the outputa = 5:

#include <iostream>
using namespace std;struct X {
private:int a;
public:void Set_a(int a) {// The 'this' pointer is used to retrieve 'xobj.a'// hidden by the automatic variable 'a'this->a = a;}void Print_a() { cout << "a = " << a << endl; }
};int main() {X xobj;int a = 5;xobj.Set_a(a);xobj.Print_a();
}

In the member function Set_a(), the statement this->a =a uses the this pointer to retrieve xobj.a hiddenby the automatic variable a.

Unless a class member name is hidden, using the class member name is equivalent to using the class member name with thethis pointer and the classmember access operator (->).

this Pointer

The this pointer is a pointer accessible only within the nonstatic member functions of aclass, struct, or union type. It points to the object for which the member function is called. Static member functions do not have athis pointer.

this
this->member-identifier
Remarks


An object's this pointer is not part of the object itself; it is not reflected in the result of asizeof statement on the object. Instead, when a nonstatic member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function. For example, the following function call:

myDate.setMonth( 3 );

can be interpreted this way:

setMonth( &myDate, 3 );

The object's address is available from within the member function as the this pointer. Most uses of this are implicit. It is legal, though unnecessary, to explicitly usethis when referring to members of the class. For example:

void Date::setMonth( int mn )
{month = mn;            // These three statementsthis->month = mn;      // are equivalent(*this).month = mn;
}

The expression *this is commonly used to return the current object from a member function:

return *this;

The this pointer is also used to guard against self-reference:

if (&Object != this) {
// do not execute in cases of self-reference

Note

Because the this pointer is nonmodifiable, assignments to this are not allowed. Earlier implementations of C++ allowed assignments tothis.

Occasionally, the this pointer is used directly — for example, to manipulate self-referential data structures, where the address of the current object is required.

Example


#include <iostream>
#include <string.h>using namespace std;class Buf
{
public:Buf( char* szBuffer, size_t sizeOfBuffer );Buf& operator=( const Buf & );void Display() { cout << buffer << endl; }private:char*   buffer;size_t  sizeOfBuffer;
};Buf::Buf( char* szBuffer, size_t sizeOfBuffer )
{sizeOfBuffer++; // account for a NULL terminatorbuffer = new char[ sizeOfBuffer ];if (buffer){strcpy_s( buffer, sizeOfBuffer, szBuffer );sizeOfBuffer = sizeOfBuffer;}
}Buf& Buf::operator=( const Buf &otherbuf )
{if( &otherbuf != this ) {if (buffer)delete [] buffer;sizeOfBuffer =  strlen( otherbuf.buffer ) + 1; buffer = new char[sizeOfBuffer];strcpy_s( buffer, sizeOfBuffer, otherbuf.buffer );}return *this;
}int main()
{Buf myBuf( "my buffer", 10 );Buf yourBuf( "your buffer", 12 );// Display 'my buffer'myBuf.Display();// assignment opperatormyBuf = yourBuf;// Display 'your buffer'myBuf.Display();
}

Output

my buffer
your buffer

/**********************************
C++ this指针的用法this指针的含义及其用法:
1.  this指针是一个隐含于每一个成员函数中的特殊指针。它指向正在被该成员函数操作的那个对象。
2.  当对一个对象调用成员函数时,编译程序先将对象的地址赋给this指针,然后调用成员函数,每次成员函数存取数据成员时,由隐含使用this指针。
3.  当一个成员函数被调用时,自动向它传递一个隐含的参数,该参数是一个指向这个成员函数所在的对象的指针。
4.  在C++中,this指针被隐含地声明为: X *const this,这意味着不能给this 指针赋值;在X类的const成员函数中,this指针的类型为:const X* const,这说明this指针所指向的这种对象是不可修改的(即不能对这种对象的数据成员进行赋值操作);
5.  由于this并不是一个常规变量,所以,不能取得this的地址。
6.  在以下场景中,经常需要显式引用this指针(1) 为实现对象的链式引用(如例Person);(2) 为避免对同一对象进行赋值操作(如例Location);(3) 在实现一些数据结构时,如list.
***********************************/
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;class Person
{public:typedef enum{BOY = 0,GIRL = !BOY} SexType;public:Person(char *n, int a, SexType s){name = new char[strlen(n)+1]; //这里的 name 等价于this->namestrcpy(name,n); //这里的 name 等价于this->nameage = a; //这里的 age 等价于this->agesex = s; //这里的 sex 等价于this->sex}int get_age(void) const{//age++; //compile error, 因为 age等价于this->age,而 get_age又是一个const成员函数,//不能对 this指针所指向的这种对象进行修改,这也是const的一个作用。//这样做的好处是,增加了代码的健壮性。return age;}Person& add_age(int a){age +=a;return *this; // 返回本对象的引用}private:char *name;int age;SexType sex;
};void TestPerson(void)
{Person UESTC("UESTC", 2013-1956, Person::BOY);cout<<"UESTC.age = "<<UESTC.get_age()<<endl;cout<<"UESTC.add_age ="<<UESTC.add_age(1).get_age()<<endl;
}
class Location
{int X,Y;//默认为私有的public:void init(int x,int y) { X =x; Y = y;};void assign(Location& pointer);int GetX(){ return X; }int GetY(){ return Y; }
};void Location::assign(Location& pointer)
{if(&pointer!=this) //同一对象之间的赋值没有意义,所以要保证pointer不等于this{X=pointer.X;Y=pointer.Y;}
}
void Test_location()
{Location x;x.init(5,4);Location y;y.assign(x);cout<<"x.X = "<<x.GetX()<<"  x.Y = "<<x.GetY()<<endl;cout<<"y.X = "<<y.GetX()<<"  y.Y = "<<y.GetY()<<endl;
}
int main(void)
{cout<<"-----TestPerson()------\n";TestPerson();cout<<"-----TestLocation()------\n";Test_location();
}
/****************************
running result:
-----TestPerson()------
UESTC.age = 57
UESTC.add_age =58
-----TestLocation()------
x.X = 5  x.Y = 4
y.X = 5  y.Y = 4Process returned 0 (0x0)   execution time : 0.031 s
Press any key to continue.
******************************/

C++读书笔记之this指针的用法相关推荐

  1. c语言指针读书笔记,《C与指针》读书笔记一

    我平时不太看书.倒不是我没有读书的习惯.而是如今的社会知识传播的方式太多.书已经不是唯一知识的载体.至于"书是人类知识的阶梯"这句名言的时代已经过去了.每天各种微信公众号推介的文章 ...

  2. 【读书笔记】【程序员的自我修养 -- 链接、装载与库(三)】函数调用与栈(this指针、返回值传递临时对象构建栈、运行库与多线程、_main函数、系统调用与中断向量表、Win32、可变参数、大小端

    文章目录 前言 介绍 内存 内存布局 栈与调用惯例 堆与内存管理 运行库 入口函数和程序初始化 C/C++运行库 运行库与多线程 C++全局构造与析构 fread 实现 系统调用与API 系统调用介绍 ...

  3. Android智能指针——读书笔记

    目录结构 目录结构 参考资料 概述 背景知识 GC经典问题 轻量级指针 实现原理分析 构造函数 析构函数 应用实例分析 强指针和弱指针 强指针的实现原理分析 增加对象的弱引用计数 增加对象的强引用计数 ...

  4. c语言指针读书笔记,《C与指针》读书笔记九

    原标题:<C与指针>读书笔记九 指针之所以在C语言中占据很大分量,是因为指针有很大的灵活性.指针以结构体结合确实为程序的编写提供了一把锋利无比的宝剑.在有些资料上介绍结构体是多种数据集合, ...

  5. 《征服C指针》读书笔记

    <征服C指针>读书笔记 评价 对于学习过C语言和C++的,<征服C指针>推荐一读,能明白一些指针深层次的一些知识点,对于一些知识有一种顿悟的感觉.如果C语言不熟或者是初学者就没 ...

  6. 读书笔记:编写高质量代码--web前端开发修炼之道(二:5章)

    读书笔记:编写高质量代码--web前端开发修炼之道 这本书看得断断续续,不连贯,笔记也是有些马虎了,想了解这本书内容的童鞋可以借鉴我的这篇笔记,希望对大家有帮助. 笔记有点长,所以分为一,二两个部分: ...

  7. C++ Primer 第三版 读书笔记

    1.如果一个变量是在全局定义的,系统会保证给它提供初始化值0.如果变量是局部定义的,或是通过new表达式动态分配的,则系统不会向它提供初始值0 2.一般定义指针最好写成:" string * ...

  8. 《数据结构与算法 Python语言描述》 读书笔记

    已经发布博客 <数据结构与算法 Python语言描述> 读书笔记 第二章 抽象数据类型和Python类 2.1 抽象数据类型abstract data type:ADT 2.1.1 使用编 ...

  9. 《Real-Time Rendering 4th Edition》读书笔记--简单粗糙翻译 第六章 纹理 Texturing

    写在前面的话:因为英语不好,所以看得慢,所以还不如索性按自己的理解简单粗糙翻译一遍,就当是自己的读书笔记了.不对之处甚多,以后理解深刻了,英语好了再回来修改.相信花在本书上的时间和精力是值得的. -- ...

最新文章

  1. 看完让你彻底搞懂Websocket原理
  2. ali arthas 火焰图_带你上手阿里开源的 Java 诊断利器:Arthas
  3. 【luogu 3375】【模板】KMP字符串匹配
  4. Ubuntu中php.ini修改运行内存
  5. SpringBoot入门和配置
  6. stm32 之引脚和各功能模块间关系
  7. 使用ueditor实现多图片上传案例——截取字符串层Util(SubString_text)
  8. c语言复合语句开始标记字符,国家开放大学C语言程序设计A第一次形考任务及答案(2020年整理)(7页)-原创力文档...
  9. audio.js – 随时随地,播放 HTML5 的声音
  10. 190521每日一句
  11. exe4j生成的exe反编译
  12. Axure rp 8 基本用法图解之一
  13. Hive教程(08)- JDBC操作Hive
  14. android仿微信选择器同时展示视频和图片
  15. [SageMath] 关于SageMath本地环境的搭建与基本使用
  16. 程炳皓:我不恨陈一舟 开心网做不好是我自己的问题
  17. 深信服easyconnect下载_深信服新一代数据防泄密解决方案荣登数安天下榜中榜
  18. 【工具】1343- NVS —— js 实现的node版本管理工具
  19. 最美的十大经典爱情句子{转}
  20. tomcat 设置缓存大小

热门文章

  1. 通过深度Q网络DQN构建游戏智能体
  2. 数字形态学滤波matlab,数字形态学滤波器与智能车路径记忆
  3. 智慧教室系统--重点设备监控系统
  4. Adversarial Attack on Attackers: Post-Process to Mitigate Black-Box Score-Based Query Attacks
  5. 光缆常用的设备测试方法介绍
  6. 阿里云mysql端口管理_怎样更改数据库端口号
  7. 1.5_18:鸡尾酒疗法(NOIP)
  8. 虚拟现实中漫游方式的分类
  9. 来看看国外DBA的工资
  10. 基于Python的银行信用卡欺诈预测模型设计 文档+任务书+项目源码及数据