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

你可能感兴趣的文章
Nginx配置TCP代理指南
查看>>
Nginx配置代理解决本地html进行ajax请求接口跨域问题
查看>>
Nginx配置参数中文说明
查看>>
Nginx配置好ssl,但$_SERVER[‘HTTPS‘]取不到值
查看>>
Nginx配置实例-负载均衡实例:平均访问多台服务器
查看>>
Nio ByteBuffer组件读写指针切换原理与常用方法
查看>>
NIO Selector实现原理
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>