C++ this指针:用于在成员函数中指向调用该函数的对象
2024-08-07
32
C++中this指针是一个指向当前对象的指针。在成员函数中,可以使用this指针来访问调用该函数的对象的成员变量和成员函数。
一、定义和使用this指针
this指针是在成员函数内部定义的一个常量指针。它存储了当前对象的地址,可以通过它访问当前对象的成员变量和成员函数。在成员函数内,无需显式地传入this指针,编译器会自动将当前对象的地址赋给this指针。
下面是一个使用this指针的例子:
class Person { public: void setName(const std::string& name) { this->name = name; } std::string getName() const { return this->name; } private: std::string name; }; Person person; person.setName("Tom"); std::cout << person.getName() << std::endl; // 输出Tom
在setName函数内部,this指针被用来访问成员变量name。这里this->name等价于成员变量name。在getName函数内部,this指针被用来访问成员函数getName()。这里this->getName()等价于调用成员函数getName()。
二、作为返回值的this指针
this指针可以作为返回值返回。这种情况下,返回的是指向调用该函数的对象的指针。为了实现这个功能,需要将返回类型设置为类的引用或指针类型。下面是一个例子:
class Person { public: Person& setName(const std::string& name) { this->name = name; return *this; } std::string getName() const { return this->name; } private: std::string name; }; Person person; person.setName("Tom").setName("Jerry"); std::cout << person.getName() << std::endl; // 输出Jerry
在setName函数内部,返回的是指向调用该函数的对象的指针。这里使用了*this来访问调用该函数的对象。
三、作为函数参数的this指针
this指针也可以作为函数参数传递。这种情况下,可以在函数内部访问其他对象的成员变量和成员函数。下面是一个例子:
class Person { public: void setName(const std::string& name) { otherPerson.setName(name); } std::string getName() const { return this->name; } private: std::string name; Person otherPerson; }; Person person; person.setName("Tom"); std::cout << person.getName() << std::endl; // 输出Tom std::cout << person.otherPerson.getName() << std::endl; // 输出Tom
在setName函数内部,将传入的name参数设置到了otherPerson对象的name成员变量中。在getName函数内部,使用了this指针访问调用该函数的对象的成员变量name。
四、总结
this指针在C++中是一个非常重要的概念,可以用来访问调用该函数的对象,作为返回值返回,或者作为函数参数传递。掌握this指针的使用可以帮助我们更好地编写面向对象的程序。
更新于:1个月前赞一波!4
相关文章
- js 遍历数组、对象的几种方式
- PHP 函数传值和传引用的区别
- PHP 可变函数
- 解释函数 foo() {} 和 var foo = function() {} 之间 foo 用法的差异
- PHP 子类重写父类成员详解 overwrite
- JavaScript 常用自定义功能函数
- PHP 常用功能函数
- 腾讯云对象存储COS及CDN加速配置
- 阿里云对象存储OSS及CDN加速配置
- PHP的数组排序函数
- TP6.0 获取请求对象的五种方式
- TP6.0 助手函数 env()
- PHP的七个数组指针函数
- Vue组件的data必须是一个函数、单个根元素、局部组件
- PHP对象传值 - 引用传值
- PHP 创建目录函数封装
- ThinkPHP6.0 公共函数文件
- 七牛云对象存储KoDo及CDN加速配置
- json python中的转储函数
- 地图函数在 Python 中有什么用?
文章评论
全部评论