this指针

1 this指针简介

关于this指针有如下几点需要注意:

  • 在类的静态成员函数中,不能使用this指针!
  • this不能指向其他对象,堪称“永不迷失的真爱”。

2 this指针的常用用法

2.1 用于访问类的成员

Human::Human(int age, int salary) {
	cout << "调用自定义的构造函数" << endl;
	this->age = age;      //this是一个特殊的指针,指向这个对象本身
	this->salary = salary;
	name = "无名";

	addr = new char[64];
	strcpy_s(addr, 64, "China");
}

2.2 返回当前对象的指针

const Human*  Human::compare1(const Human * other) {
	if (age > other->age) {
		return  this; //没有创建新的对象
	}
	else {
		return other;
	}
}

2.3 返回当前对象的引用

const Human&  Human::compare2(const Human& other) {
	if (age > other.age) {
		return *this;  //访问该对象本身的引用,而不是创建一个新的对象
	}
	else {
		return other;
	}
}

参考资料:

  1. C/C++从入门到精通-高级程序员之路【奇牛学院】
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值