13~C++ this指针

1. this 指针引入

this指针 表示成员函数实际调用时,对象在内存中的位置

//basic.cpp
#include <iostream>
using namespace std;
class HeyBaby{
public:
	HeyBaby(int x, int y) : cute_score (x), nauty_score(y){
	cout << "constructor this& = " << this << endl;
	}
	void baby_show()
	{
		cout << "cute score =  " << cute_score << "  nauty score = " << nauty_score << endl; 
		cout << "this& = " << this << endl;
	}
	int cute_score;
	int nauty_score;
};
int main (void)
{
	HeyBaby Baby(100,99);
	Baby.baby_show();
	cout << "Baby address = " << &Baby << endl;
	return 0;
}

输出:
constructor this& = 0x7fff63e4fe10
cute score = 100 nauty score = 99
this& = 0x7fff63e4fe10
Baby address = 0x7fff63e4fe10

2. this指针常量属性, this指针带有常属性和不带有常属性形成重载

#include <iostream>
using namespace std;
class HeyBaby{
public:
	HeyBaby(int x, int y) : cute_score (x), nauty_score(y){
	cout << "constructor this& = " << this << endl;
	}
	
	void baby_change (void) const {
		//cute_score++; 这样写编译器会报错
		cout << "this function could not change the member of this class" << endl;	
	}
	void baby_change (void) {
		cute_score++;
		cout << "this function could change the member of this class" << endl;
	}
	int cute_score;
	int nauty_score;
};
int main (void)
{

	HeyBaby Baby_boy(100,99);
	Baby_boy.baby_change();
	
	HeyBaby const Baby_girl (100, 100);	
	Baby_girl.baby_change();
	return 0;
}

constructor this& = 0x7ffe867b66d0
this function could change the member of this class
constructor this& = 0x7ffe867b66e0
this function could not change the member of this class

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值