✨✨小新课堂开课了,欢迎欢迎~✨✨
🎈🎈养成好习惯,先赞后看哦~🎈🎈
所属专栏:C++:由浅入深篇
小新的主页:编程版小新-CSDN博客
1.初步认识面向过程和面向对象
面向过程:我们之前学习的C语言就是面向过程,以过程为中心,强调函数的实现,将问题分解为一系列的过程,然后调用函数解决问题。
面向对象:C++是基于面向对象的,强调的是对象与对象的联系,将问题分解为一系列相互协作的对象,每个对象都有自己的状态和行为。
举例说明面向过程和面向对象的区别。
我们以借书为例。
借书分为三个过程:用户找借书机构,根据书名搜索图书,利用图书ID和用户ID借书。我们关注的是这三个过程。
借书也可以抽离出三个对象:书,用户,图书馆。我们关注的是这三个对象之间的联系。
更具体的去解释就是,在面向过程的编程中,我们可能需要创建多个函数来处理不同的任务,比如searchBook(title)根据图书搜索书名,borrowBook(bookID,userID)利用图书ID和用户ID借书,listAvailiableBooks()图书馆提供的可借阅书籍。调用这三个函数就能解决借书问题。
在面向对象的编程中,我们会创建几个类来封装数据和行为。
图书类:包含书名,以及借阅的方法。
用户类:用户的信息,以及借书的方法。
图书馆类:管理图书集合和用户集合,提供搜索,借阅图书的方法。
对比:
2.类的引入
在C语言中,结构体中只能定义变量,但在C++中,结构体内不仅可以定义变量,还可以定义函数。C++兼容C语言中struct的用法,struct升级成了类。
2.1类的两种定义
第一种:用struct定义类。
#include<iostream>
using namespace std;
// C++将struct升级成了类
// 1、类里面可以定义函数
// 2、struct名称就可以代表类型
// C++兼容C中struct的用法
typedef struct ListNodeC
{
//变量
struct ListNodeC* next;
int val;
}LTNode;
// 不再需要typedef,ListNodeCPP就可以代表类型
struct ListNodeCPP
{
//函数
void Init(int x)
{
next = nullptr;
val = x;
}
//变量
ListNodeCPP* next;
int val;
};
但是一般情况下,我们更推荐使用第二种。
第二种:用class定义类
其语法的基本结构如下
class className
{
//类体:由成员函数和成员变量组成
};
#include<iostream>
using namespace std;
class Data
{
int a;
int b;
};
2.2单文件和多文件书写
类的声明和定义可以放在一个文件书写,也可以放在不同的文件中书写。
1.将声明和定义全放在类体内,编译器会将定义在类体内的成员函数默认为内联函数处理。
#include<iostream>
using namespace std;
class Data
{
//声明和定义放在一起
int ADD(int x, int y)
{
return x + y;
}
int a;
int b;
};
2.将声明放在.h文件中,定义放在.cpp文件中。要注意的是成员函数名前需要加类名: :。
#include<iostream>
using namespace std;
#include"test.h"
//test.h
class Data
{
//声明
int ADD(int x, int y);
int a;
int b;
};
//test.cpp
//定义
int Data::ADD(int x, int y)
{
return x + y;
}
注意:在一般练习时,我们更习惯于将声明和定义放在类内,但是在实际工程中,更倾向于采用第二种。
2.3成员变量的命名
#include<iostream>
using namespace std;
class Date
{
void Init(int year, int month, int day)
{
//命名冲突
year = year;
month = month;
day = day;
}
int year;
int month;
int day;
};
如果对成员变量加以修饰的话,在视觉上就会很好的区分。
#include<iostream>
using namespace std;
class Date
{
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
int _year;
int _month;
int _day;
};
3.类的成员访问限定符及封装
3.1访问限定符
在C++中类有三种访问限定符:public,private,protected。他们的作用各不相同。
public修饰的成员在类外可以直接被访问;protected和private修饰的成员在类外不能直接被访问;protected和private是⼀样的,以后继承章节才能体现出他们的区别。
3.2访问限定符的访问权限作用域
访问权限作用域从该访问限定符出现的位置开始直到下一个访问限定符出现时为止,如果后面有访问限定符,作用域就到 }即类结束。
3.3类的封装
![](https://i-blog.csdnimg.cn/direct/69f98a1b7a3c497fbfd2755e75d53a25.jpeg)
3.4类域
#include<iostream>
using namespace std;
class Stack
{
public:
// 成员函数
void Init(int n = 4);
private:
// 成员变量
int* array;
size_t capacity;
size_t top;
};
// 声明和定义分离,需要指定类域
void Stack::Init(int n)
{
array = (int*)malloc(sizeof(int) * n);
if (nullptr == array)
{
perror("malloc申请空间失败");
return;
}
capacity = n;
top = 0;
}
int main()
{
Stack st;
st.Init();
return 0;
}
4.类的实例化
Data::_year = 2024;//error,并没有分配空间,不能初始化
![](https://i-blog.csdnimg.cn/direct/517d4852c4a24560949210a2e1c1b39e.png)
5.类对象模型
我们首先来思考一些问题,一个类中既有成员变量,又有成员函数,那一个类对象中有什么呢?我们该如何计算类对象的大小呢?
5.1类对象的存储方式猜测
![](https://i-blog.csdnimg.cn/direct/6ea0b6cdfbe14c6fac951286dc394b15.png)
![](https://i-blog.csdnimg.cn/direct/08862c69a984489aa1052cbde6b8b844.png)
![](https://i-blog.csdnimg.cn/direct/45b41b3c4c53439897bdfb70d4ca4c6c.png)
5.2类对象的大小
C++规定,实例化的对象要采用内存对齐的方式存储。
内存对齐规则• 第一个成员在与结构体偏移量为0的地址处。• 其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处。• 注意:对齐数 = 编译器默认的⼀个对齐数与该成员大小的较小值。• VS中默认的对对齐为8• 结构体总大小为:最大对齐数(所有变量类型最大者与默认对齐参数取最小)的整数倍。• 如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最大对齐数的整数倍处,结构体的整体大小就是所有最大对齐数(含嵌套结构体的对齐数)的整数倍。
#include<iostream>
using namespace std;
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d;
cout << sizeof(d) << endl;
return 0;
}
运行结果:
接下来我们看一个比较特殊的例子,如果类里面没有成员变量,只有成员函数,或者什么都没有呢?对象的大小是多少?
#include<iostream>
using namespace std;
class B
{
public:
void Print()
{
//...
}
};
class C
{};
int main()
{
B b;
C c;
cout << sizeof(b) << endl;
cout << sizeof(c) << endl;
return 0;
}
运行结果:
6.this指针
6.1this指针的引入
我们来看下面一段代码
#include<iostream>
using namespace std;
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类实例化出对象d1和d2
Date d1;
Date d2;
d1.Init(2024, 3, 31);
d1.Print();
d2.Init(2024, 7, 5);
d2.Print();
return 0;
}
C++编译器给每个“非静态的成员函数”增加了一个隐藏的指针参数,让该指针指向当前对象,类的成员函数中访问成员变量,本质上都是通过this指针访问的。只不过所有操作对用户是透明的,即用户不需要来传递,而是编译器自动完成。
#include<iostream>
using namespace std;
class Date
{
public:
// void Init(Date* const this, int year, int month, int day)
void Init(int year, int month, int day)
{
//this->_year = year;
_year = year;
//this->_month = month;
_month = month;
//this->_day = day;
_day = day;
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
// 这里只是声明,没有开空间
int _year;
int _month;
int _day;
};
int main()
{
// Date类实例化出对象d1和d2
Date d1;
Date d2;
// d1.Init(&d1, 2024, 3, 31);
d1.Init(2024, 3, 31);
//d1.Print(&d1)
d1.Print();
// d2.Init(&d2, 2024, 7, 5);
d2.Init(2024, 7, 5);
//d2.Print(&d2)
d2.Print();
return 0;
}
上述代码调用成员函数传参时,看似只传入了一些基本数据,实际上还传入了指向该对象的指针。
6.2this指针的特性
1.this指针不能修改:this指针的类型为**const**2.this指针只能在成员函数内部使用3.对象中并不存储this指针:this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参4.this指针不需要用户传递:this指针是成员函数第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,
#include<iostream>
using namespace std;
class A
{
public:
void Print()
{
cout << "A::Print()" << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->Print();
return 0;
}
这里我们可能会理解成对空指针解引用导致运行崩溃,其实不然,程序是正常运行的。这里并没有对空指针p进行解引用,因为Print等成员函数地址并没有存到对象里面,成员函数的地址是存在公共代码段的。虽然表面看上去是解引用,但实际上编译器不需要通过解引用去找对应函数,只需要去公共代码区执行对应函数即可。
#include<iostream>
using namespace std;
class A
{
public:
void Print()
{
cout << "A::Print()" << endl;
cout << _a << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->Print();
return 0;
}
![](https://i-blog.csdnimg.cn/direct/15b6f5494e9044efac8932e9693ecb23.png)
![](https://i-blog.csdnimg.cn/direct/12293b2915744c9b862047b0223a36c9.png)
7.C++和C语言实现Stack的简单对比
通过下面两份代码对比,我们发现C++实现Stack形态上还是发生了挺多的变化,底层和逻辑上没啥变化。
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
void STPush(ST* ps, STDataType x)
{
assert(ps);
// 满了, 扩容
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity *
sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
int main()
{
ST s;
STInit(&s);
STPush(&s, 1);
STPush(&s, 2);
STPush(&s, 3);
STPush(&s, 4);
while (!STEmpty(&s))
{
printf("%d\n", STTop(&s));
STPop(&s);
}
STDestroy(&s);
return 0;
}
C++实现:
#include<iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
// 成员函数
void Init(int n = 4)
{
_a = (STDataType*)malloc(sizeof(STDataType) * n);
if (nullptr == _a)
{
perror("malloc申请空间失败");
return;
}
_capacity = n;
_top = 0;
}
void Push(STDataType x)
{
if (_top == _capacity)
{
int newcapacity = _capacity * 2;
STDataType* tmp = (STDataType*)realloc(_a, newcapacity *
sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
_a = tmp;
_capacity = newcapacity;
}
_a[_top++] = x;
}
void Pop()
{
assert(_top > 0);
--_top;
}
bool Empty()
{
return _top == 0;
}
int Top()
{
assert(_top > 0);
return _a[_top - 1];
}
void Destroy()
{
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
private:
// 成员变量
STDataType * _a;
size_t _capacity;
size_t _top;
};
int main()
{
Stack s;
s.Init();
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
while (!s.Empty())
{
printf("%d\n", s.Top());
s.Pop();
}
s.Destroy();
return 0;
}