博客
关于我
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/

你可能感兴趣的文章
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node
查看>>
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
node+express+mysql 实现登陆注册
查看>>
Node+Express连接mysql实现增删改查
查看>>
node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
查看>>
Node-RED中Button按钮组件和TextInput文字输入组件的使用
查看>>
vue3+Ts 项目打包时报错 ‘reactive‘is declared but its value is never read.及解决方法
查看>>
Node-RED中Slider滑杆和Numeric数值输入组件的使用
查看>>
Node-RED中Switch开关和Dropdown选择组件的使用
查看>>
Node-RED中使用exec节点实现调用外部exe程序
查看>>