C++ ——— this 指针的引出以及在类中如何正确使用

目录

this 指针的引出

经典面试题


this 指针的引出

代码演示:

class Data
{
public:
	// 初始化
	void Init(int year = 1946, int month = 2, int day = 14)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	// 打印
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Data d1;
	
	d1.Init(2024, 12, 9);
	d1.Print();

	return 0;
}

以上是一个简单的日期类,在类中的成员函数的参数中,还隐藏了一个参数,那就是 this 指针

也就是说 Init 函数其实有 4 个参数,Print 函数有 1 个参数

这个参数就是 Data* this ,这个参数是编译器加上的,而且在函数中,也是通过 this 指针进行访问的年月日,并且在调用主函数时,也加上的对象的地址的

以上的代码原本的样子:

class Data
{
public:
	// 初始化
	void Init(Data* this, int year = 1946, int month = 2, int day = 14)
	{
		this->_year = year;
		this->_month = month;
		this->_day = day;
	}

	// 打印
	void Print()
	{
		cout << this->_year << "/" << this->_month << "/" << this->_day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Data d1;
	
	d1.Init(&d1, 2024, 12, 9);
	d1.Print(&d1);

	return 0;
}

以上只是编译器自动加上 this 指针的一系列操作,但是在实际中不能在形参或者实参中手动加上 this 指针,加上就会报错,但是能在类中使用 this 指针

加上就会报错:

在类中使用 this 指针指向变量(正常运行):

这也进一步证明了 this 指针的存在


经典面试题

代码演示:

class A
{
public:
	void Print()
	{
		cout << "void Print()" << endl;
	}

private:
	int _a;
};

int main()
{
	A* p = nullptr;

	p->Print();

	return 0;
}

问:以上代码编译的结果为?

A. 编译报错
B. 程序崩溃
C.正常运行

正确答案是:C

解析:

虽然 p 是空指针,但是调用函数不需要在 p 中找函数地址,因为在上一章就讲解到了类里面的成员函数不是独立的,而是放在公共代码段的,所以当执行 p->Print() 这句代码的时候,是直接在公共代码段调用了 Print 函数,所以可以正常运行

代码验证:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值