C++学习笔记(二十四):c++ this

  • this指针在c++中较为常用。this是一个指向当前对象实例的指针,通过this指针,可以访问该类的成员函数。
  • 示例如下:
  • this指针主要的使用场景是在类内部调用类外部的函数,该函数传递的参数是调用该函数的类对象,代码示例如下:
cpp 复制代码
#include<iostream>
class Entity;
void PrintEntity(Entity* e);

class Entity
{
public:
	int x, y;
	Entity(int x, int y)
	{
		//使用this指针,this表示当前Entity类对象的实例指针
		this->x = x;
		PrintEntity(this);
	}
}; 

void PrintEntity(Entity* e)
{
	std::cout << e->x << std::endl;
}

int main()
{
	Entity e1(5, 10);
	std::cout << e1.x << std::endl;

	std::cin.get();
	return 0;
}
相关推荐
会周易的程序员13 小时前
cNetgate插件架构设计详解 动态库 脚本二开lua, python, javascript
javascript·c++·python·物联网·lua·iot
普通网友13 小时前
C++与Rust交互编程
开发语言·c++·算法
weixin_4481199413 小时前
Datawhale 硅基生物进化论 202602第3次笔记
笔记
xyty332013 小时前
QImageReader 的全局静态锁原理
c++·windows·qt
散峰而望13 小时前
【算法竞赛】堆和 priority_queue
开发语言·数据结构·c++·算法·贪心算法·动态规划·推荐算法
adore.96813 小时前
2.20 oj83+84+85
c++·复试上机
alexwang21114 小时前
B2007 A + B 问题 题解
c++·算法·题解·洛谷
winfreedoms14 小时前
ROS2坐标转换,正解反解——黑马程序员ROS2课程上课笔记(5)
人工智能·笔记
春和景明36014 小时前
复习数据库
学习
wostcdk14 小时前
数论学习1
数据结构·学习·算法