博客
关于我
C++_类_this指针
阅读量:288 次
发布时间:2019-03-01

本文共 1096 字,大约阅读时间需要 3 分钟。

定义

在C++中,`this`是一个指向对象的常指针。它的主要作用是方便程序员能够引用当前对象本身的成员。这种设计目的是为了让开发者能够简化代码书写,避免了在构造函数中使用`this`关键字的麻烦。

作用

1、避免构造器的入参与成员名相同

在C++中,如果一个构造函数的参数名称与类的成员名称相同,直接使用参数名进行赋值会导致编译错误。为了解决这个问题,开发者可以使用`this`指针来访问对象本身的成员。例如:
#include 
using namespace std;class Stu {public: Stu(string name, int age) { this->name = name; this->age = age; } void prin() { cout << name << age << endl; }};

2、支持多重赋值

在某些情况下,我们需要对同一个对象进行多次赋值操作。基于`this`指针的赋值运算符重载能够实现这一点。例如:
#include 
using namespace std;class String {public: String(const String& another) { if (another._str == _str) { return *this; } delete[] _str; _str = new char[another._str.size()]; memcpy(_str, another._str.c_str(), another._str.size()); return *this; }};

3、`this`指针的本质

在C++中,`this`实际上是一个指向`Stu`对象的常指针,即`Stu* const this`。需要注意的是,`this`指针的不可变性可以通过两种方式体现: - `Stu* const this;`:指针本身不可被修改。 - `const Stu* this;`:指针指向的对象及其成员不可被修改。

例如:

Stu* const growUp() {    this->age++;    return this;}

通过以上内容可以看出,this指针在C++编程中具有重要的功能,广泛应用于构造函数的参数传递、多重赋值以及确保代码的可靠性等方面。

转载地址:http://psko.baihongyu.com/

你可能感兴趣的文章
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用json节点解析JSON数据
查看>>
Node-RED中使用node-random节点来实现随机数在折线图中显示
查看>>
Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
查看>>
Node-RED中使用node-red-contrib-image-output节点实现图片预览
查看>>
Node-RED中使用node-red-node-ui-iframe节点实现内嵌iframe访问其他网站的效果
查看>>
Node-RED中使用Notification元件显示警告讯息框(温度过高提示)
查看>>
Node-RED中实现HTML表单提交和获取提交的内容
查看>>
Node-RED中建立Websocket客户端连接
查看>>
Node-RED中通过node-red-ui-webcam节点实现访问摄像头并截取照片预览
查看>>
node-request模块
查看>>