类与对象(随心记录一)

1:C++中struct和class的区别是什么?

因为C++是需要兼容C语言的,所以C++中的struct可以当作结构体来使用,这里我们创建一个“日期”结构体

#include<iostream>
using namespace std;

struct Date
{
	int _year;
	int _month;
	int day;
};

int main(void)
{
	Date a;
	a._year = 2022, a._month = 12, a.day = 14;
	printf("%d %d %d", a._year, a._month, a.day);
	
	return 0;
}

在C语言中直接Date a是会报错的,但C++不会,结构体也可以用类的方式来定义。

运行结果:

 然后struct的成员默认访问方式是public,而class的成员默认访问方式是private。

在类和对象阶段,我们只研究类的封装特性,那么什么是封装呢?

封装:隐藏对象的属性和实现细节,仅仅对外公开接口来和对象进行交互

类的作用域

#include<iostream>
using namespace std;

class Date
{
public:
	void Print();
	void Init(int year, int month, int days);
private:
	int _year;
	int _month;
	int _days;
};

void Date::Print()
{
	cout << _year << " " << _month << " " << _year << " " << endl;
}

void Date::Init(int year, int month, int days)
{
	_year = year;
	_month = month;
	_days = days;
}

int main(void)
{
	Date a;
	a.Init(2022, 12, 14);
	a.Print();
	return 0;
}
类定义了一个新的作用域 ,类的所有成员都在类的作用域中 在类体外定义成员,需要使用 :: 作用域解析符来指明成员属于哪个类域

类对象的存储方式猜测:

缺陷:每个对象中成员变量是不同的,但是调用同一份函数,如果按照此种方式存储,当一个类创建多
个对象时, 每个对象中都会保存一份代码,相同代码保存多次,浪费空间。那么如何解决呢?
只保存成员变量,成员函数存放在公共的代码段

 

this指针

this 指针的特性
1. this 指针的类型:类类型 * const
2. 只能在 成员函数 的内部使用
3. this 指针本质上其实是一个成员函数的形参 ,是对象调用成员函数时,将对象地址作为实参传递给 this形参。所以对象中不存储 this 指针
4. this 指针是成员函数第一个隐含的指针形参,一般情况由编译器通过 ecx 寄存器自动传递,不需要用户 传递

我们先定义一个日期类:

#include<iostream>
using namespace std;

class Date
{
public:
	void Print();
	void Init(int year, int month, int days);
private:
	int _year;
	int _month;
	int _days;
};

void Date::Print()
{
	cout << _year << " " << _month << " " << _year << " " << endl;
}

void Date::Init(int year, int month, int days)
{
	_year = year;
	_month = month;
	_days = days;
}

int main(void)
{
	Date d1,d2;
	d1.Init(2022, 12, 13);
	d2.Init(2022, 12, 14);
	d1.Print();
	d2.Print();
	return 0;
}

在Date日期类中有两个函数,Init和Print,那么函数是怎么判断要设置哪个对象中呢?

C++ 中通过引入 this 指针解决该问题,即: C++ 编译器给每个 非静态的成员函数 增加了一个隐藏的指针参 数,让该指针指向当前对象 ( 函数运行时调用该函数的对象 ) ,在函数体中所有成员变量的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成

接下来我们来进行验证,给出以下代码:

#include<iostream>
using namespace std;

class Date
{
public:
	void Print();
	void Init(int year, int month, int days);
private:
	int _year;
	int _month;
	int _days;
};

void Date::Print()
{
	cout << _year << " " << _month << " " << _year << " " << endl;
}

void Date::Init(int year, int month, int days)
{
	_year = year;
	_month = month;
	_days = days;
}

int main(void)
{
	Date* p = NULL;
	p->Init(1, 2, 3);
	p->Print();
	return 0;
}

定义一个空指针的类,NULL被this指针接收了,当调用函数的时候,由于空指针不能被操作,所以程序是会崩溃的。

猜你喜欢

转载自blog.csdn.net/AkieMo/article/details/128315601