0
点赞
收藏
分享

微信扫一扫

【C++】——类与对象(上)

文章目录

1. 前言

今天我们来学习C++初期最重要的知识点,类与对象,因为类与对象涉及的知识太多,所以我将分为上中下三个部分来为大家讲解类与对象。

2. 面向过程和面向对象

下面我以洗衣服来举例说明面向过程和面向对象的区别:

3. 类的引入

//成员变量和成员函数
struct Stack
{
	void Init()
	{
		a = 0;
		top = capacity = 0;
	}
	void Push(int x)
	{
	
	}
	void Pop()
	{
	
	}

	int* a;
	int top;
	int capacity;
};

int main()
{
	Stack st;
	st.Init();

	return 0;
}

4. 类的定义

class className
{
	// 类体:由成员函数和成员变量组成
};  // 一定要注意后面的分号

4.1 类的俩种定义方式

5. 类的访问限定符及封装

5.1 类的访问限定符

访问限定符说明:

5.2 封装

6. 类的作用域

7. 类的实例化

int main()
{
	Person p1;//类的实例化
	Person p2;//实例化的每个Person对象成员变量都是独立空间,是不同的变量,但每个Person对象调用的成员函数都是同一个
	Person p3;
	p1.PrintPersonInfo();
	return 0;
}

8. 类对象的存储方式

class A
{
public:
	void Print()
	{
		cout << a << endl;
	}

	void Func()
	{
		cout << "A::Func" << endl;
	}
private:
	char a;
	int b;
};

int main()
{
	cout << sizeof(A) << endl;
	
	A* ptr = nullptr;
	ptr->Func();//正常运行,编译链接时就根据函数名去公共代码区找到了函数的地址,再call函数。
	
	return 0;
}

在这里插入图片描述

9. this指针

比如我们现在定义了这样一个类:

class Date
{
public:
	void Init(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	void Print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d;
	d.Init(2023, 4, 27);
	d.Print();
	return 0;
}

以上代码会被编译器转换成下面的样子:


class Date
{
public:
	void Init(Date* const this, int year, int month, int day)
	{
		this->_year = year;
		this->_month = month;
		this->_day = day;
	}

	void Print(Date* const this)
	{
		cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d;
	d.Init(&d,2023, 4, 27);
	d.Print(&d);
	return 0;
}

9.1 this指针特性

10. 结尾

类与对象是C++初学阶段最重要的一块知识点,此处概念和细节非常多,大家在学习的过程中也要认真,并且要多复习这里的内容。
最后,感谢各位大佬的耐心阅读和支持,觉得本篇文章写的不错的朋友可以三连关注支持一波,如果有什么问题或者本文有错误的地方大家可以私信我,也可以在评论区留言讨论,再次感谢各位。

举报

相关推荐

0 条评论