C++对象模型和this指针

发布于:2024-04-29 ⋅ 阅读:(39) ⋅ 点赞:(0)

一.C++对象模型

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

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

--->空对象:

#include <iostream>
using namespace std;
class Person
{

};
void test01()
{
	Person p;
	cout << sizeof(p) << endl;//1
}
int main()
{
	test01();
	return 0;
}

#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指针

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

//用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;
}
//返回对象本身用*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指针)

//空指针访问成员函数
#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;
}

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