41.this指针

this指针永远指向当前对象

成员函数通过this指针即可知道操作的是那个对象的数据。This指针是一种隐含指针,它隐含于每个类的非静态成员函数中。This指针无需定义,直接使用即可。

注意:静态成员函数内部没有this指针,静态成员函数不能操作非静态成员变量。

this指针的使用

当形参和成员变量同名时,可用this指针来区分
在类的非静态成员函数中返回对象本身,可使用return *this
 

// 38.this.cpp : 定义控制台应用程序的入口点。
//

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

// this可以解决命名冲突
class Person
{
public:
	Person(int age)
	{
		this->age = age;
	}

	//对比年龄
	void compareAge(Person & p)
	{
		if (this->age == p.age)
		{
			cout << "年龄相等" << endl;;
		}
		else
		{
			cout << "年龄不相等" << endl;;
		}
	}

	//年龄相加
	Person& PlusAge(Person & p)
	{
		this->age += p.age;
		return *this; //*this指向对象本体
	}

	int age;
};

void test01()
{
	Person p1(10);

	cout << "p1的年龄" << p1.age << endl;//p1的年龄10

	Person p2(10);

	p1.compareAge(p2);

	p1.PlusAge(p2).PlusAge(p2).PlusAge(p2); //链式编程

	cout << "p1的年龄" << p1.age << endl;
}

int main(){

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

输出

p1的年龄10
年龄相等
p1的年龄40

空指针访问成员函数

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Person
{
public:

	void show()
	{
		cout << "Person show" << endl;
	}
	void showAge()
	{
		if (this == NULL)//防止空指针异常
		{
			return;
		}
		cout << this->m_Age << endl; // NULL -> m_Age
	}

	int m_Age; // 
};

void test01()
{
	Person * p = NULL;
	p->show();//Person show
	p->showAge();//

}

int main(){
	test01();


	system("pause");
	return EXIT_SUCCESS;
}

const修饰成员函数

用const修饰的成员函数时,const修饰this指针指向的内存区域,成员函数体内不可以修改本类中的任何普通成员变量。

当成员变量类型符前用mutable修饰时例外

常函数  void func() const {} 常函数
常函数 修饰是this指针  const Type * const this
常函数 不能修改this指针执行的值
常对象 在对象前 加入 const修饰 const Person p1
常对象 不可以调用普通的成员函数
常对象 可以调用常函数
用mutable修饰的关键字是在常函数可以修改的
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Person
{
public:
	Person()
	{
		//构造中修改属性
		//this 永远执行本体  

		this->m_A = 0;
		this->m_B = 0;
	}

	void showInfo() const //常函数 不允许修改指针指向的值
	{
		//this->m_A = 1000;
		this->m_B = 1000;
		// const Person * const this
		cout << "m_A = " << this->m_A << endl;//m_A = 0
		cout << "m_B = " << this->m_B << endl;//m_B = 1000
	}

	void show2() const
	{
		//m_A = 100;
	}

	int m_A;
	mutable int m_B; //就算是常函数 我还是执意要修改

};

void test01()
{

	Person p1;
	p1.showInfo();

	//常对象 不允许修改属性
	const  Person p2;
	cout << "p2.m_A = " << p2.m_A << endl;//p2.m_A = 0
	p2.show2();
	//常对象 不可以调用普通成员函数
	//常对象 可以调用常函数
}

int main(){

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值