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;
}

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

相关推荐
神仙别闹10 分钟前
基于QT(C++)实现Windows 自启动项查看和分析
c++·windows·qt
lzhdim23 分钟前
C# 中读取CPU、硬盘和内存温度
开发语言·c#
Irene199125 分钟前
Oracle PL/SQL Developer 版本差异(11g、14)实战总结
java·开发语言
qq_4480111633 分钟前
C语言中的getchar()
c语言·开发语言
肖志-AI全栈38 分钟前
JavaScript 快速排序:从 pivot、双指针到分治思想
开发语言·javascript·排序算法
WWTYYDS_6661 小时前
ProtoBuf超详细使用教程
c++
野生风长1 小时前
c++类和对象(this指针,重载operator,习题总结)
java·开发语言·c++
雪的季节1 小时前
Python「假多态」与 C++「真多态」的核心区别
开发语言·c++
zmzb01031 小时前
C++课后习题训练记录Day166
开发语言·c++
皓月斯语2 小时前
程序设计语言的特点
开发语言·数据结构·c++