c++对象模型和this指针(基于黑马程序员的视频)

成员变量和成员函数存储的问题

#include <iostream>
#include <stdio.h>
using namespace std;
//在C++中,类内的成员变量和成员函数分开存储
//只有非静态成员变量才属于类的对象上 
class Person{
	int m_a;//只有非静态成员变量才属于类的对象,才会分配空间 
	static int m_b;
	void func(){
	}
	static void m_func(){
	}
};
int Person::m_b=0;
//当为空对象时,编译器会分配一个内存空间,区分空对象占内存的位置
//每个空对象也应该有一个独一无二的位置 
void test01(){
	Person a;
	cout <<sizeof(a);
}
int main(){
	test01();
	return 0;
}

this指针的用途

#include <iostream>
#include <stdio.h>
using namespace std;
//编码规范:类属性都加上m_
//this指针的用途:
//当形参和成员变量同名时,可用this指针来区分
//在类的非静态成员函数中返回对象本身,可使用return *this
class Person {
public:
	Person(int age) {
		this->age = age;
	}
	int age;
	//引用返回本体
	Person& PersonAddPerson(Person& a)
	{
		age += a.age;
		//返回对象本身
		return *this;
	}
};
void test01() {
	Person p1(10);
	Person p2(10);
	//实现链式编程
	p1.PersonAddPerson(p2).PersonAddPerson(p2);
	cout << p1.age;
}
int main() {
	test01();


	return 0;
}

空指针访问成员函数的问题

#include <iostream>
#include <stdio.h>
using namespace std;
//空指针访问成员函数,应该加以判断增加健壮性
class Person {
public:
	void showclass() {
		cout << "this is Person class" << endl;
	}
	void showAge() {
		if (this == nullptr)  return;
		cout << m_Age;
	}
	int m_Age;
};
void test01() {
	Person* p = nullptr;
	p->showclass();
	p->showAge();
}
int main() {
	test01();
	return 0;
}

常对象和常成员函数

#include <iostream>
#include <stdio.h>
using namespace std;
//const 修饰成员函数 和修饰对象

class Person {
public:
	Person() {
		m_a = 100;
		m_b = 100;
	}
	//首先 this指针的本质是一个指针常量 ,它的指向不能够改变
	//const 修饰成员函数之后,表示this指针是一个常量指针,其指向的值也不能够修改
	void showPerson()  const
	{
		//m_a = 100;不可修改
		m_b = 100;
		//this =NULL 错误,this指针的本质
	}
	void func() {

	}
	int m_a;
	mutable int m_b;//如果想要在const函数修改它,加上关键字mutable
};
void test01() {
	Person p;
	p.showPerson();
}
void test02() {
	const Person p;//在对象前加const ,变成常对象
	p.m_b = 100;
	p.showPerson();
	//常对象只能调用常函数,普通函数中可以修改变量的值
	//p.func();
}
int main() {
	test01();
	test02();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值