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
相关推荐
肆忆_5 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星9 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc