黑马程序员匠心之作-4.3对象模型和this指针

 4.3.1成员变量和成员函数分开存储

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

2、只有非静态成员变量在类上

3、当一个类中没有成员变量和成员函数时,仍然占一个字节的内存空间,目的是区分不同的空类

4.3.2this指针概念

#include<iostream>
#include<string>
using namespace std;
//class Person {
//	int a;//非静态成员变量不属于类上
//	static int b;//静态成员变量属于类
//	void fun();//非静态成员函数不属于类
//	static void fun1();//静态成员函数不属于类;
//
//};
class Person
{
public:

	int age;
	Person(int age)
	{
		//age = age;//形参与成员变量名称相同的时候,名称冲突赋值出错;
		//this指针用来解决名称冲突问题;
		this->age = age;
		
	}
	//注意这里要以引用的方式返回,才能一直返回P1本身;若以值的方式返回,
    //则每次都会在另一个内存创建一个和传入相同的对象,不能改动P1原本的值;
	Person& Personaddage(Person& P)
	{
		this->age += P.age;
		return *this;
	}
};
void test01()
{
	Person P(18);

	cout << "P年龄:" << P.age << endl;

}
void test02()
{
	Person P1(10);
	Person P2(20);
	//链式编程的思想:可以不断的返回本身并且追加操作;
	P1.Personaddage(P2).Personaddage(P2).Personaddage(P2).Personaddage(P2).Personaddage(P2);
	cout << "P1年龄:" <<P1.age<< endl;
}
int main()
{
	test02();
	system("pause");
	return 0;
}

 4.3.3空指针访问成员函数

#include<iostream>
#include<string>
#include"point.h"
#include"Circle.h"
using namespace std;
//class Person {
//	int a;//非静态成员变量不属于类上
//	static int b;//静态成员变量属于类
//	void fun();//非静态成员函数不属于类
//	static void fun1();//静态成员函数不属于类;
//
//};
class Person
{
public:
	void showname()
	{
		cout << "打印名称" << endl;
	}
	void showage()

	{
		if (this == NULL)//加判断来增强代码的健壮性,当指针为NULL时,return不返回任何值
		{
			return;
		}
		cout << "年龄:" << m_age << endl;//相当于this->m_age:当this为NULL时,不能访问成员变量
	}
	int m_age;
};
void test01()
{
	Person *P=NULL;
	P->showage();
}

int main()
{
	test01();
	system("pause");
	return 0;
}

4.3.4const修饰成员函数

 

#include<iostream>
#include<string>
#include"point.h"
#include"Circle.h"
using namespace std;

class Person
{
public:
	
	void showage()const//加const的成员函数被称为常函数

	{
		b = 90;
		//m_age = 100;//成员函数后面加指针修饰的是this,故此时this指向的值也不能改变
		//系统默认是this->m_age=100;
		//this=NULL;//错误写法,this本质为指针常量。即指针的指向不能修改;Person*const this
		//若想让指针指向的值也不能修改,要在前面加一个const修饰变为const Person*const this,即在函数的后面加const变为常函数
	}
	void fun()
	{

	}
	int m_age;
	mutable int b;//mutable关键字可以使得常函数改变该成员变量;
};
void test01()
{
	Person p;
}
void test02()
{
	const Person P;
	//P.m_age = 10;
	P.b = 100;//常对象只能访问mutable修饰的成员变量;
	//P.fun();//常对象只能调用常函数


}

int main()
{
	test02();
	system("pause");
	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值