C++对象模型和this指针

一.C++对象模型

--->成员变量和成员函数时分开储存的(在C++中,类内的成员变量和成员函数分开储存,

只有非静态成员变量才属于类的对象上)

--->空对象:

cpp 复制代码
#include <iostream>
using namespace std;
class Person
{

};
void test01()
{
	Person p;
	cout << sizeof(p) << endl;//1
}
int main()
{
	test01();
	return 0;
}
cpp 复制代码
#include <iostream>
using namespace std;
class Person
{
public:
	int m_A;//非静态成员变量,属于类的对象上
	static int m_B;//静态成员变量,不属于类的对象上
	void func() {};//非静态成员函数,不属于类的对象上
};
int Person::m_B = 0;//(类内声明,类外初始化)
void test01()
{
	Person p;
	cout << sizeof(p) << endl;//4
}
int main()
{
	test01();
	return 0;
}

用sizeof()计算类所占的空间时,只计算属于类的对象上的!!!!!!!!!!!!!!!!

!!!!!!!只有非静态成员变量属于类的对象上!!!!!!!

二.this指针

--->指向被调用的成员函数所属的对象

cpp 复制代码
//用this指针解决名称冲突
#include <iostream>
using namespace std;
class Person
{
public:
	Person(int age)//有参构造函数
	{
		this->age = age;//this指针指向的是被调用的成员函数所属的对象,谁调用了这个有参构造,this指针就指向谁
	}
	int age;//成员变量与形参撞名
};
void test01()
{
	Person p(18);
	cout << "p的年龄为:" << p.age << endl;
}
int main()
{
	test01();
	return 0;
}
cpp 复制代码
//返回对象本身用*this
#include <iostream>
using namespace std;
class Person
{
public:
	Person(int age)
	{
		this->age = age;
	}
	Person& PersonAddAge(Person& p)
	{
		this->age += p.age;
		return *this;//返回本身才能实现叠加操作(链式编程思想)
	}
	int age;
};
void test01()
{
	Person p1(10);
	Person p2(20);
	p2.PersonAddAge(p1);
	cout << p2.age << endl;//30
}
int main()
{
	test01();
	return 0;
}

--->链式编程思想:

必须要指针的指针才能对p2进行修改,否则return的只是p2的副本

三.空指针访问成员函数

(C++空指针可以调用成员函数,但要注意有没有用到this指针)

cpp 复制代码
//空指针访问成员函数
#include <iostream>
using namespace std;
class Person
{
public:
	void showPerson()
	{
		cout << "This is Person class" << endl;
	}
	void showPersonAge()
	{
		cout << "age=" << m_Age << endl;//等价于this->m_Age
	}
	int m_Age;//非静态成员变量,属于类的对象上,编译器不知道年龄属于哪个对象
};
void test01()
{
	Person* p=NULL;
	p->showPerson();//正常运行
	p->showPersonAge();//报错(原因:传入指针为空)
}
int main()
{
	test01();
	return 0;
}

--->改进:(若为空指针,直接返回,不进行访问)

相关推荐
Alair‎2 小时前
【无标题】
开发语言
Mr.Jessy5 小时前
JavaScript高级:构造函数与原型
开发语言·前端·javascript·学习·ecmascript
云栖梦泽7 小时前
鸿蒙应用签名与上架全流程:从开发完成到用户手中
开发语言·鸿蒙系统
爱上妖精的尾巴7 小时前
6-4 WPS JS宏 不重复随机取值应用
开发语言·前端·javascript
小鸡吃米…9 小时前
Python 列表
开发语言·python
kaikaile19959 小时前
基于C#实现一维码和二维码打印程序
开发语言·c#
我不是程序猿儿10 小时前
【C#】画图控件的FormsPlot中的Refresh功能调用消耗时间不一致缘由
开发语言·c#
rit843249910 小时前
C# Socket 聊天室(含文件传输)
服务器·开发语言·c#
kk哥889910 小时前
C++ 对象 核心介绍
java·jvm·c++
helloworddm10 小时前
WinUI3 主线程不要执行耗时操作的原因
c++