C++中类的this指针

指向当前类对象的指针

C++中类的this指针是指向当前类对象的指针,我们首先创建一个类myclass,定义一个非静态成员函数test,在其中打印一下this的地址,并在主函数中创建一个对象,打印一下对象的地址:

cpp 复制代码
#include <iostream>

class myclass {
public:
	void test() {
		std::cout << "this addr:" << this << std::endl;
	}
};

int main() {
	myclass mc;
	mc.test();
	std::cout << "mc addr:" << &mc << std::endl;
	return 0;
}
bash 复制代码
// 执行结果:
this addr:0000006F53B2FC98
mc addr:0000006F53B2FC98

我们可以发现两者相同。

隐式指针参数

this是编译器为每个非静态成员函数隐式添加的指针参数(可以理解为函数的默认参数,不用我们显式传递),因此我们在类的非静态成员函数中可以直接访问该类的成员变量。在上面myclass中定义两个成员变量x、y,我们可以在成员函数中访问并修改成员变量的值:

cpp 复制代码
#include <iostream>

class myclass {
public:
	void modifyValue() {
		this->x = 10;
		this->y = 20;
	}
	void printValue() {
		std::cout << "x:" << this->x << std::endl;
		std::cout << "x:" << this->y << std::endl;
	}
private:
	int x{ 0 }, y{ 0 };
};

int main() {
	myclass mc;
	mc.modifyValue();
	mc.printValue();
	return 0;
}
bash 复制代码
// 执行结果:
x:10
x:20

当然编译器为我们提供了便利,我们还可以在非静态成员函数中直接访问成员变量:

cpp 复制代码
#include <iostream>

class myclass {
public:
	void modifyValue() {
		x = 10;
		y = 20;
	}
	void printValue() {
		std::cout << "x:" << x << std::endl;
		std::cout << "x:" << y << std::endl;
	}
private:
	int x{ 0 }, y{ 0 };
};

int main() {
	myclass mc;
	mc.modifyValue();
	mc.printValue();
	return 0;
}
bash 复制代码
// 执行结果:
x:10
x:20
相关推荐
CoderIsArt3 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
AI情绪识别开源6 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
「QT(C++)开发工程师」7 小时前
C++ auto 用法详解
开发语言·c++
OPEN-F7 小时前
C++STL教程:容器适配器与实用工具
开发语言·c++
yaoxin5211237 小时前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言
OPEN-F7 小时前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++
有点。7 小时前
C++二叉搜索树进阶
开发语言·c++
HugoStudio_SWAN7 小时前
【擦除重绘】C++ 控制台动画:弹跳 Logo DVD 屏保效果
开发语言·c++·学习·程序人生
kyle~9 小时前
C++_STL---迭代器失效
开发语言·c++