C++学习记录---成员函数与成员对象、this指针、空指针、const修饰成员函数

一、成员变量与成员函数分开存储

一个空对象占据1个字节

非静态成员变量,属于该类的对象上
静态成员变量,不属于该类的对象上

非静态成员函数,不属于该类的对象上
静态成员函数,不属于该类的对象上

class Person
{
	int m_a; //非静态成员变量
	static int m_b; //静态成员变量
	void func(){} //非静态成员函数
	static void func2(){} //静态成员函数
}
void test()
{
	cout<<"size of p:"<< sizeof(p) <<endl;
}
int main()
{
	Person p;
	test();
	
	return 0;
}

二、this指针概念

this指针可以解决多个对象对同一个函数的调用问题
this指针是隐含每一个非静态成员函数内的一种指针
this指针不需要定义,直接使用

用途:this指针指向被调用的成员函数所属于的对象
1.当形参和成员变量同名时,可以用this指针来区分
2.在类的非静态成员函数中返回对象本身,可以使用return *this

class Person
{
public:
	Person(int age)
	{
		//age = age; //此时没有对 int age 中的age进行赋值
		this->age = age;//this指针指向被调用的成员函数所属于的对象
	}
	Person &perAddage(Person &p)
	{
		this->age += p.age;
		return *this;
	}
	int age;
}
void test01()
{
	Person p1(20);
	cout<<"p1的年龄:"<< p1.age <<endl;
}
void test02()
{
	Person p1(10);
	Person p2(20);
	p2.personAddage(p1).personAddage(p1).personAddage(p1);
	cout << "p2的年龄:"<< p2.age << endl;
}
int main()
{
	test01();
	test02();
	
	return 0;
}

三、空指针调用成员函数

class Person
{
public:
	void showPersonName()
	{
		cout<<"this is show name"<<endl;
	}
	void showPersonAge()
	{
		if (this == NULL)
		{
			return;
		}
		cout<<"age = "<< this->age <<endl;;
	}
	int age;
}
void test01()
{
	this->showPersonName();
	this->showPersonAge();
}

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

四、const修饰成员函数

常函数:
成员函数后加const后我们称这个函数为常函数
常函数内不可以修改成员属性
成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
声明对象前加const称该对象为常对象
常对象只能调用常函数

class Person
{
public:
	//this指针的本质,是指针常量,指针的指向是不可以修改的
	//const Person * const this
	//在成员函数后加const,修饰的是this指向,让指针指向的值也不可以修改
	void showPerson() const
	{
		//this->m_A = 100;//无法修改
		//this->NULL;//无法修改
		this->m_B = 100;
	}
	void func()
	{}
	
	int m_A;
	mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值
}
void test01()
{
	Person p;
	p.showPerson;
}
void test02()
{
	const Person p1;
	p1.m_B = 100;//在常对象下可以修改
	
	//常对象只能调用常函数
	p1.showPerson();
	//p.func();//无法调用普通成员函数,因为普通成员函数可以修改属性,二常对象无法修改属性
}

int main()
{
	test01();
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值