博客
关于我
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 集群配置方式 静态文件处理
查看>>
Nginx+Django-Python+BPMN-JS的整合工作流实战项目
查看>>
Nginx+Keepalived+LVS集群实战
查看>>
Nginx+Keepalived实现简单版高可用主备切换
查看>>
Nginx+Lua 开发高性能Web应用实战
查看>>
nginx+mysql+redis+mongdb+rabbitmq 自动化部署脚本
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
nginx+tomcat单个域名及多个域名配置
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>