指向当前类对象的指针

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

#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;
}
// 执行结果:
this addr:0000006F53B2FC98
mc addr:0000006F53B2FC98

我们可以发现两者相同。

隐式指针参数

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

#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;
}
// 执行结果:
x:10
x:20

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

#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;
}
// 执行结果:
x:10
x:20
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐