2021-11-2 this 指针 / 空指针访问成员函数/ const 常函数 常对象 /

//************ this 指针
//多个成员调用同一个成员函数,如何区分是谁在调用这个成员函数
//谁调用这个成员函数,成员函数里面的this指针就指向谁
//1.解决名称冲突
//2.返回对象本身用 *this

class Person
{
public :
	//1.名称冲突  成员变量和传入变量的命名一致,导致运行错误
	//Person(int age)
	//{
	//	age = age;
	//}
	//int age;

	//上述问题的解决方案,this指向 调用该成员函数的对象
	Person(int age)
	{
		this->age = age;
	}

	//void PersonAddAge(Person& p)
	//{
	//	this->age += p.age;
	//}
	Person& PersonAddAge(Person& p)
	{
		this->age += p.age;
		return *this;  
	}
	int age;
};

void test()
{
	Person p1(18);
	cout << "p1.age = " << p1.age << endl;
}

void test02()
{
	Person p1(10);
	cout << "p1.age = " << p1.age << endl;
	Person p2(10);

	p1.PersonAddAge(p2);
	
	//下面会报错,因为p1.PersonAddAge(p2);返回的是一个void类型,如果要进行下面的才做,就需要返回成员函数本身
	p1.PersonAddAge(p2).PersonAddAge(p2).PersonAddAge(p2);
	cout << "p1.age = " << p1.age << endl;
}

int main()
{
	test();
	test02();
	return 0;
}

//************ 空指针调用成员函数
class Person
{
public:
	void showName()
	{
		cout << " this is showName" << endl;
	}

	void showAge()
	{
		if (this == NULL)
		{
			return;
		}
		cout << " this is showAge" << m_age << endl;  //m_age  == this -> m_age,this如果是空的,是无法访问里面的成员的
	}

	int m_age;
};


void test()
{
	Person* p = NULL;  //定义了一个空指针

	p->showName();
	p->showAge();   //这里是会报错的,
}

int main()
{
	test();
	return 0;
}

//************ const 修饰成员函数 常函数   const修饰对象,常对象
//常函数
//1.成员函数后面加cosnt 称为常函数
//2.常函数内不可以修改成员属性
//3.成员属性声明加关键字mutable之后,常函数中仍然可以修改
//常对象,声明对象前加const 称该对象为常对象
//常对象只能调用常函数

class Person
{
public:
	//每一个成员函数内部都有一个this指针
	//this 指针的本质,是指针常量,该指针的指向是不可以修改的,但是指针的指向的值是可以修改的
	//void showPerson() const之后,指针指向的值也将无法修改
	void showPerson()   const
	{
	/*	this->m_age = 100;*/
		m_b = 100;
		cout << " this is showName" << endl;
	}

	//常对象只能调用常函数
	void func()
	{

	}

	int m_age;
	mutable int m_b;    //即使在常函数中也可以修改他的值
};


void test()
{
	Person p; 
	p.showPerson();
}

//常对象
void test02()
{
	
	const Person p;
	p.m_a = 100;  //报错,由于const对对象p的修饰,将无法修改
	p.m_b = 100;  //这个依然可以修改

	 //常对象只能调用常函数,func是普通的函数,普通函数里面是可以修改成员的属性,但是常函数里面是不可以修改成员函数的属性的
	//两者是矛盾的
	p.func();  
}
int main()
{
	test();
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值