当前位置:   article > 正文

C++ 笔记

C++ 笔记

一、跳转语句(goto 语句)

作用:可以无条件跳转语句

语法: goto 标记;

解释:如果标记的名称存在、执行到goto语句时。会跳转到标记的位置。

  1. #include<iostream>
  2. using namespace std;
  3. int mian(){
  4.     cout << "1" << endl;
  5. goto flag;
  6.     //下面三行代码将不执行
  7. cout << "2" << endl;
  8. cout << "3" << endl;
  9. cout << "4" << endl;
  10. flag: // 将跳到这里执行 注意这里是冒号
  11. cout << "5" << endl;
  12. system("pause");
  13. return 0;
  14. }

结果为:

1

5

二.数组

所谓数组,就是一个集合,里面存放了相同类型的数据元素。

特点1:数组中的每个数据元素都是相同的数据类型

特点2:数据是由连续的内存位置组成的

### 一维数组

## 一维数组的定义方式

一维数组的定义的三种方式:

1. 数据类型 数组名[数组长度];

2. 数据类型 数组名[数组长度] ={值1,值2,...};

3. 数据类型 数组名[] = {值1,值2,...};

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. //第一种定义方法: 数据类型 数组名[数组长度];
  5. int arr[3];
  6.     // 给数组种的元素赋值
  7. arr[0] = 10;
  8. arr[1] = 20;
  9. arr[2] = 30;
  10.     //遍历数据元素
  11. for (int i = 0; i < 3; i++) { //注意: 数组的下标是从0开始索引的
  12. cout << arr[i]<< " "; //结果为:10 20 30
  13. }
  14.     
  15.     cout << endl;
  16.     // ----------------------------------------
  17.     //第二种定义方式: 数据类型 数组名[数组长度] ={值1,值2,...};
  18.    
  19.     int arr2[3] = {10,20,30};  // 如果{}内的数据个数不足数组的下标数,剩余数组数据用0补全
  20.     //遍历数据元素
  21. for (int i = 0; i < 3; i++) { //注意: 数组的下标是从0开始索引的
  22. cout << arr2[i]<< " "; //结果为:10 20 30
  23. }
  24.    
  25.     cout << endl;
  26.     //---------------------------------------
  27.     // 第三种定义方式: 数据类型 数组名[] = {值1,值2,...};
  28.    
  29.     int arr3[] = {10,20,30};
  30.    
  31.     //遍历数据元素
  32. for (int i = 0; i < 3; i++) { //注意: 数组的下标是从0开始索引的
  33. cout << arr3[i]<< " "; //结果为:10 20 30
  34. }
  35.     cout << endl;
  36. system("pause");
  37. return 0;
  38. }

## 一维数组数组名

一维数组名称的用途:

  1. 可以统计整个数组在内存中的长度

  1. 可以获取数组在内存中的首地址

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. // 数组名的用途
  5. // 1.可以获取整个占用内存空间大小
  6. int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
  7.     // sizeof用法:
  8.     // 在 C/C++ 中,sizeof() 是一个判断数据类型或者表达式长度的运算符。
  9.     // 详细请到 https://blog.csdn.net/weixin_39598135/article/details/111011490
  10. cout << "整个数组所占内存空间为: " << sizeof(arr) << endl; // 40
  11. cout << "每个元素所占的空间为: " << sizeof(arr[0]) << endl; // 4
  12. cout << "数组的元素的个数:" << sizeof(arr) / sizeof(arr[0]) << endl; // 10
  13. // 2. 可以通过数组名获取到数组首地址
  14. cout << "数组首地址为: " << (int)arr << endl; // arr数组首地址
  15.     cout << "数组中第一个元素地址为: "<< (int)&arr[0] <<endl;
  16.     // 两个结果相同
  17.    
  18. system("pause");
  19. return 0;
  20. }

//注:数组名是常量,不可以进行赋值操作

如: arr = 100; //错误

## 练习案例

# 1. 五只小猪称体重
  1. // 题目:五只小猪称体重
  2. // 描述:在一个数组中记录了五只小猪的体重, 如:int arr[5] = {300,350,200,400,250};
  3. // 找出并打印最重的小猪体重。
  4. #include<iostream>
  5. using namespace std;
  6. int main() {
  7. int arr[5] = { 300,350,200,400,250 };
  8. int max=0;
  9. for (int i = 0; i < 5; i++) {
  10. if (max < arr[i]) {
  11. max = arr[i];
  12. }
  13. }
  14. cout << "最重的小猪: " << max << endl; // 400
  15. system("pause");
  16. return 0;
  17. }

# 2. 数组元素逆置
  1. //题目: 数组元素逆置
  2. //描述: 请声明一个5个元素的数组,并且将元素逆置
  3. // 如原数组元素为:1,2,3,4,5; 逆置后输出结果为:4,5,2,3,1;
  4. #include<iostream>
  5. using namespace std;
  6. int main(){
  7. int arr[5] = { 1,2,3,4,5 };
  8. int start = 0; //起始元素下标
  9. int end = sizeof(arr) / sizeof(arr[0]) - 1; //末尾数组下标
  10. int temp = 0; //中间变量
  11. for (int i = 0; i < (sizeof(arr) / sizeof(arr[0]) /2); i++) {
  12. temp = arr[i];
  13. arr[i] = arr[end - i];
  14. arr[end - i] = temp;
  15. }
  16. for (int i = 0; i < end + 1; i++) {
  17. cout << arr[i] << " ";
  18. } // 5 4 3 2 1
  19. system("pause");
  20. return 0;
  21. }

## 冒泡排序

  1. // 利用冒泡排序实现升序序列
  2. #include<iostream>
  3. using namespace std;
  4. int main() {
  5. int arr[] = { 4,2,1,3,6,7,9,8,5 };
  6. int temp = 0;
  7. int number = sizeof(arr) / sizeof(arr[0]);
  8. cout << "排序前:" << endl;
  9. for (int i = 0; i < number; i++) {
  10. cout << arr[i] << " "; //1 2 3 4 5 6 7 8 9
  11. }
  12. for (int i = 0; i < number - 1; i++) { // 排序轮数
  13. for (int j = 0; j < number - i - 1; j++) {
  14. if (arr[j] > arr[j + 1]) {
  15. temp = arr[j];
  16. arr[j] = arr[j + 1];
  17. arr[j + 1] = temp;
  18. }
  19. }
  20. }
  21. cout << endl;
  22. cout << "排序后:" << endl;
  23. for (int i = 0; i < number; i++) {
  24. cout << arr[i] << " "; //1 2 3 4 5 6 7 8 9
  25. }
  26. system("pause");
  27. return 0;
  28. }

### 二维数组

## 二维数组 的定义方式

二维数组定义的四种方式:

  1. 数据类型 数组名[行数][列数];

  1. 数据类型 数组名[行数][列数] = { {数据1,数据2},{数据3,数据四 }};

  1. 数据类型 数组名[行数][列数] = { 数据1,数据2,数据3,数据四 };

  1. 数据类型 数组名[][列数] = { 数据1,数据2,数据3,数据四 };

注1:数组行数、列数的下标是从第0行第0列开始的;

注2:在定义二维数组时,如果初始化了数据,可以省略行数;

## 二维数组数组名

1.查看二维数组所占内存空间

2.获取二维数组的首地址

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. int arr[2][3] = {
  5. {1,2,3},
  6. {4,5,6}
  7. };
  8. cout << "二维数组所占空间大小: " << sizeof(arr) << endl; //4*6 =24
  9. cout << "二维数组一行所占空间大小: " << sizeof(arr[0]) << endl; // 4*3 =12
  10. cout << "二维数组一个元素所占空间大小: " << sizeof(arr[0][0]) << endl; //4
  11. // 可以查看二维数组的首地址
  12. cout << "二维数组首地址: " << (int)arr << endl;
  13. cout << "二维数组的第一行首地址: " << (int)arr[0] << endl;
  14. cout << "二维数组的第一个元素地址: " << (int)&arr[0][0] << endl;
  15.     // 结果相同
  16. system("pause");
  17. return 0;
  18. }

## 练习案例

  1. // 题目: 考试成绩统计
  2. // 描述: 有三名同学(张三,李四,王五),在一次考试中的成绩分别如下表;
  3.         语文 数学 英语
  4. 张三 {100,100,100},
  5. 李四 {90, 50, 100},
  6. 王五 {60, 70, 80}
  7. //请分别输出 三名同学的总成绩;
  8. #include<iostream>
  9. using namespace std;
  10. int main() {
  11. int student[3][3] = {
  12. {100,100,100},
  13. {90,50,100},
  14. {60,70,80}
  15. };
  16. string name[3] = { "张三","李四","王五" };
  17. for (int i = 0; i < 3; i++) {
  18.         int sum = 0;
  19. for (int j = 0; j < 3; j++) {
  20. sum += student[i][j];
  21. }
  22. cout << name[i] << "的总成绩:"<< sum << endl;
  23.         //张三的总成绩:300
  24.         //李四的总成绩:240
  25.         //王五的总成绩:210
  26. }
  27. system("pause");
  28. return 0;
  29. }

三.函数

## 值传递

  • 所谓值传递,就是函数调用时实参将数值传入给形参

  • 值传递时,如果形参发生改变,并不影响实参

  1. #include<iostream>
  2. using namespace std;
  3. // 当函数不要返回值,定义的时候可以写void
  4. void swap(int num1, int num2) {
  5. cout << "交换前:" << endl;
  6. cout << "num1 = " << num1 << endl; //10
  7. cout << "num2 = " << num2 << endl; //20
  8. int temp = 0;
  9. temp = num1;
  10. num1 = num2;
  11. num2 = temp;
  12. cout << "交换后:" << endl;
  13. cout << "num1 = " << num1 << endl; //20
  14. cout << "num2 = " << num2 << endl; //10
  15. //return;当定义函数时候,不需要返回值。可以不写return。
  16. }
  17. int main() {
  18. int num1 = 10;
  19. int num2 = 20;
  20. swap(num1, num2);
  21.    
  22.     cout << "----------------------------"<<endl;   
  23. cout << "num1 = " << num1 << endl; //10
  24. cout << "num2 = " << num2 << endl; //20
  25.     //实参num1 和num2的值没有发生交换
  26. system("pause");
  27. return 0;
  28. }

## 函数的分文件编写

作用: 让代码结构更加清晰

  • 函数的分文件编写一般有4个步骤

  • 1.创建后缀名为.h的头文件

  • 2.创建后缀名为.cpp的源文件

  • 3.在头文件中写函数的声明

  • 4.在源文件中写函数的定义

  1. // swap.h文件
  2. #include<iostream>
  3. using namespace std;
  4. void swap(int a, int b);
  1. //swap.cpp文件
  2. #include "swap.h"
  3. void swap1(int num1, int num2) {
  4. cout << "交换前:" << endl;
  5. cout << "num1 = " << num1 << endl;
  6. cout << "num2 = " << num2 << endl;
  7. int temp = 0;
  8. temp = num1;
  9. num1 = num2;
  10. num2 = temp;
  11. cout << "交换后:" << endl;
  12. cout << "num1 = " << num1 << endl;
  13. cout << "num2 = " << num2 << endl;
  14. //return ;当函数声明时候,不需要返回值。可以不写return。
  15. }
  16. int main() {
  17. int a = 10, b = 20;
  18. swap(a, b);
  19. system("pause");
  20. return 0;
  21. }

四.指针

  • 指针的基本概念

  • 指针的作用:可以通过指针间接访问内存

  • 指针是一个记录地址的特殊变量

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. //1.定义一个指针
  5. int a = 10;
  6. //指针定义的语法:数据类型 * 指针变量名
  7. int* p;
  8. //让指针记录变量a的地址
  9. p = &a;
  10. //2.使用指针
  11. //通过解引用的方式来找到指针指向的内存。
  12. //指针前加 * 代表解引用, 找到或修改指针指向的内存的数据
  13.  cout << a << endl; //10
  14. cout << *p << endl; //10
  15. *p = 1000;
  16. cout << a << endl; //1000
  17. cout << *p << endl; //1000
  18. system("pause");
  19. return 0;
  20. }

## 指针所占内存空间

  • 在32位操作系统下,指针是占4个字节空间大小,不管是什么数据类型

  • 在64位操作系统下,指针是占8个字节空间大小,不管是什么数据类型

## 空指针和野指针

### 空指针

  • 空指针:指针变量指向内存中的编号为0的空间

  • 用途: 初始化指针变量

  • 注意:空指针指向的内存是不可以访问的

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. //指针变量p指针指向内存地址编号的空间
  5. int* p = NULL;
  6. //访问空指针报错
  7. // 内存编号0-255为系统占用内存,不允许用户访问
  8. //cout << *p << endl; //报错
  9. system("pause");
  10. return 0;
  11. }

### 野指针

  • 野指针:指针变量指向非法的内存空间

  1. int main() {
  2. //指针变量p指向内存地址编号为Ox1100
  3. int* p = (int*)0x1100; //报错
  4. cout << *p << endl;
  5. system("pause");
  6. return 0;
  7. }

  • 总结:空指针和野指针都不是我们申请空间。因此不要访问。

## const 修饰指针

  • const 修饰指针有三种情况:

  • 1.const 修饰指针 --- 常量指针

  • 特点:指针的指向可以修改,但是指针指向的值不可以改。

  • 2.const 修饰常量 ---指针常量

  • 特点:指针的指向不可以改,指针指向的值可以改。

  • 3.const 即修饰指针又修饰常量

  • 特点:指针的指向不可以改,指针指向的值也不可以改。

  • 技巧:看const 右侧紧跟的是指针还是常量,是指针就是常量指针,是常量就是指针常量

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. //◦ 1.const 修饰指针 --- 常量指针
  5.     //特点:指针的指向可以修改,但是指针指向的值不可以改。
  6. int a = 10;
  7. int b = 20;
  8. const int* p = &a;
  9. // *p = 20;//不行
  10. p = &b;
  11. cout << *p << endl; //20
  12. //2.const 修饰常量 ---指针常量
  13.     //特点:指针的指向不可以改,指针指向的值可以改。
  14. int* const p2 = &a;
  15. *p2 = 20;
  16. //p2 = &b; //不行
  17. cout << *p2 << endl; //20;
  18. //3.const 即修饰指针又修饰常量
  19.     //特点:指针的指向不可以改,指针指向的值也不可以改。
  20. const int* const p3 = &a;
  21. //*p3 = 20; //不行
  22. //p3 = &b; //不行
  23. system("pause");
  24. return 0;
  25. }

## 指针和数组

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. //指针和数组
  5. //利用指针访问数组中的元素
  6. int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
  7. int* p = arr; //arr就是数组的首地址
  8. for (int i = 0; i < 10; i++) {
  9. cout << *p << endl;
  10. p++;
  11. }
  12. system("pause");
  13. return 0;
  14. }

## 指针和函数

  1. #include<iostream>
  2. using namespace std;
  3. //值传递
  4. void swap01(int a, int b) {
  5. int temp;
  6.     temp = a;
  7. a = b;
  8. b = temp;
  9. }
  10. //地址传递
  11. void swap02(int* a, int* b) {
  12. int temp;
  13. temp = *a;
  14. *a = *b;
  15. *b = temp;
  16. }
  17. int main() {
  18. // 1.值传递
  19. int a = 10;
  20. int b = 20;
  21. swap01(a, b);
  22. cout << a << endl; //10
  23. cout << b << endl; //20
  24. //2.地址传递
  25. //交换前:
  26. cout << a << endl; //10
  27. cout << b << endl; //20
  28. //交换后:
  29. swap02(&a, &b);
  30. cout << a << endl; //20
  31. cout << b << endl; //10
  32. system("pause");
  33. return 0;
  34. }

## 案例

  1. #include<iostream>
  2. using namespace std;
  3. void bubbleSort(int* arr, int len) { // int *arr 也可以写为int arr[]
  4.     //冒泡排序
  5. for (int i = 0; i < len - 1; i++) {
  6. for (int j = 0; j < len - 1 - i; j++) {
  7. if (arr[j] > arr[j + 1]) {
  8. int temp = arr[j + 1];
  9. arr[j + 1] = arr[j];
  10. arr[j] = temp;
  11. }
  12. }
  13. }
  14. }
  15. void printArray(int *arr,int len) {
  16. for (int i = 0; i < len; i++) {
  17. cout << arr[i] << " ";
  18. }
  19. }
  20. int main() {
  21. int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
  22. int len;
  23. len = sizeof(arr) / sizeof(arr[0]);
  24. bubbleSort(arr, len);
  25. //打印数组
  26. printArray(arr,len);
  27. system("pause");
  28. return 0;
  29. }

五.结构体

## 结构体定义和使用

  • 结构体基本概念

  • 结构体属于用户自定义的数据类型,允许用户存储不同的数据类型

  • 结构体定义的使用

  • 语法: struct 结构体名 {结构体成员列表}

  • 通过结构体创建变量的方式有三种:

  • struct 结构体 变量名

  • struct 结构体 变量名 = {成员1值,成员2值}

  • 定义结构体时顺便创建变量

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. // 创建学生数据类型: 学生包括(姓名,年龄,分数)
  5. typedef struct Student {
  6. // 成员列表
  7. string name;
  8. int age = 0;
  9. int score = 0;
  10. }STU ;
  11. struct Student1 {
  12. // 成员列表
  13. string name;
  14. int age = 0;
  15. int score = 0;
  16. }s3;
  17. int main() {
  18. STU s1;
  19. s1.name = "张三";
  20. s1.age = 18;
  21. s1.score = 100;
  22. cout << "姓名: " << s1.name << endl;
  23. cout << "年龄: " << s1.age << endl;
  24. cout << "分数: " << s1.score << endl;
  25. STU s2={"李四",19,80};
  26. cout << "姓名: " << s2.name << endl;
  27. cout << "年龄: " << s2.age << endl;
  28. cout << "分数: " << s2.score << endl;
  29. s3.name = "刘备";
  30. s3.score = 12;
  31. cout << "----------------" << endl;
  32. cout << "姓名: " << s3.name << endl;
  33. cout << "分数: " << s3.score << endl;
  34. // struct 可以省略。
  35. //struct Student1 s4;
  36. //Student1 s4;
  37. system("pause");
  38. return 0;
  39. }

  • 总结1: 定义结构体时的关键词是struct,不可省略

  • 总结2:创建结构体变量时,关键词struct 可以省略

  • 总结3:结构体变量利用操作符"."访问成员

## 结构体数组

  • 作用:将自定义的结构体放入数组中方便维护。

  • 语法:struct 结构体 数组名[元素个数] = {{},{},{}}

  1. #include<iostream>
  2. using namespace std;
  3. struct Student {
  4. string name; // 姓名
  5. int age; // 年龄
  6. int score; // 分数
  7. };
  8. int main() {
  9. struct Student arr[3] = {
  10. {"张三",18,80},
  11. {"李四",19,23},
  12. {"王五",20,12}
  13. };
  14. // 给结构体数组中的元素赋值
  15. arr[2].name = "赵六";
  16. arr[2].age = 12;
  17. arr[2].score = 212;
  18. int len = sizeof(arr) / sizeof(arr[0]);
  19. for (int i = 0; i < len; i++) {
  20. cout << "姓名: " << arr[i].name << " 年龄: " << arr[i].age << " 分数: " <<arr[i].score << endl;
  21. }
  22. system("pause");
  23. return 0;
  24. }
  25. //结果:
  26. //姓名: 张三 年龄: 18 分数: 80
  27. //姓名: 李四 年龄: 19 分数: 23
  28. //姓名: 赵六 年龄: 12 分数: 212

## 结构体指针

  • 作用:通过指针访问结构体的成员。

  • 利用操作符->可以通过结构体指针访问结构体属性。

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. typedef struct student {
  5. string name;
  6. int age;
  7. int score;
  8. }STU;
  9. int main() {
  10. STU s1 = { "张三", 18,100 };
  11. STU* p = &s1;
  12. cout << "姓名: " << p->name
  13.         << " 年龄: " << p->age
  14.         << " 分数: " << p->score <<endl;
  15. system("pause");
  16. return 0;
  17. }

## 结构体做函数参数

  • 作用:将结构体作为参数向函数中传递

  • 传递方式有两种:

  • 值传递

  • 地址传递

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. typedef struct student {
  5. string name;
  6. int age;
  7. int score;
  8. }STU;
  9. //值传递
  10. void printStudent(STU stu) {
  11. stu.age = 10;
  12. cout << "值传递中函数中年龄: " << stu.age << endl; //10
  13. }
  14. //地址传递
  15. void printStudent1(STU* p) {
  16. p->age = 112;
  17. cout << "地址传递中子函数中年龄: " << p->age << endl; //112
  18. }
  19. int main() {
  20. STU stu = { "张三",12,345 };
  21. printStudent(stu);
  22. cout << "主函数中年龄: " << stu.age << endl; //12 != 10 改变形参不改变实参
  23. printStudent1(&stu);
  24. cout << "主函数中年龄: " << stu.age << endl; //112 改变形参改变实参
  25. system("pause");
  26. return 0;
  27. }

  • 总结: 如果不想修改主函数中的数据,用值传递,反之用地址传递。

## 结构体中const 使用场景

  • 作用:用const来防止误操作

  1. #include<iostream>
  2. using namespace std;
  3. struct student {
  4. string name; //姓名
  5. int age; //年龄
  6. int socre; // 分数
  7. };
  8. //将函数中的形参改成指针,可以减少内存空间。
  9. void printfStudent(const student* stu) {
  10. //stu->age =100;//操作失败,因为加了const修改
  11. cout << "姓名: " << stu->name << " 年龄: " << stu->age << " 分数: " << stu->socre << endl;
  12. }
  13. int main() {
  14. student stu = { "张三",100,12 };
  15. printfStudent(&stu);
  16. system("pause");
  17. return 0;
  18. }

## 结构体案例

  • 案例描述:

学校正在做毕设项目,每个老师带领5个学生,总共有3名老师,需求如下:

设计学生和老师的结构体,其中在老师的结构体中,有老师姓名和一个存放5名学生的数组作为成员

学生的成员有姓名、考试分数,创建数组存放3名老师,通过函数给每个老师及所带的学生赋值

最终打印出老师数据以及老师所带的学生数据。

  1. #include<iostream>
  2. #include<string>
  3. #include<ctime>
  4. using namespace std;
  5. struct Student {
  6. string sname;
  7. int score=0;
  8. };
  9. struct Teacher {
  10. string tname;
  11. struct Student stuAArray[5];
  12. };
  13. void allocatespace(struct Teacher tArray[], int len) {
  14. string nameSeed = "ABCDE";
  15. for (int i = 0; i < len; i++) {
  16. tArray[i].tname = "Teacher_";
  17. tArray[i].tname += nameSeed[i];
  18. for (int j = 0; j < 5; j++) {
  19. tArray[i].stuAArray[j].sname = "Student_";
  20. tArray[i].stuAArray[j].sname += nameSeed[j];
  21. int random = rand() % 60 +40 ;
  22. tArray[i].stuAArray[j].score = random;
  23. }
  24. }
  25. }
  26. void printInfo(struct Teacher *tArray, int len) {
  27. for (int i = 0; i < len; i++) {
  28. cout << "老师姓名: " << tArray[i].tname << endl;
  29. for (int j = 0; j < 5; j++) {
  30. cout << "\t学生名字: " << tArray[i].stuAArray[j].sname
  31. << " 学生分数: " << tArray[i].stuAArray[j].score << endl;
  32. }
  33. }
  34. }
  35. int main() {
  36. //随机数种子
  37. srand((unsigned int)time(NULL));
  38. struct Teacher tArray[3];
  39. int len = sizeof(tArray) / sizeof(tArray[0]);
  40. allocatespace(tArray, len);
  41. printInfo (tArray,len);
  42. system("pause");
  43. return 0;
  44. }

六 .内存分区模型

  • c++程序在执行时,将内存大方向划分4个区域

  • 代码区: 存放函数体的二进制代码,有操作系统进行管理的

  • 全局区:存放全局变量和静态变量以及常量

  • 栈区:由编译区自动分配释放,存放函数的参数值,局部变量等。

  • 堆区:由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收。

  • 内存四区意义:

  • 不同区域存放的数据,赋予不同的生命周期,给我们更大的灵活编程。

  • ## 1.程序运行前

  • 在程序编译后,生成了exe可执行程序,未执行该程序前分为两个区域

  • 代码区:

  • 存放cpu执行的机器指令

  • 代码区是共享的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份代码即可

  • 代码区是只读的,使其只读的原因是防止程序意外地修改了它的指令。

  • 全局区:

  • 全局变量和静态变量存放在此。

  • 全局区还包括了常量区,字符串常量和const 修饰的全局变量也存放在此。

  • 该区域的数据在程序结束后操作系统释放。

  • 总结:

  • c++中在程序运行前分为全局区和代码区;

  • 代码区特点是共享和只读

  • ## 2.程序运行后

  • 栈区:

  • 由编译区自动分配释放,存放函数的参数值 局部变量等

  • 注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放。

  • 堆区:

  • 由程序员分配释放,若程序员不释放,程序结束时,有操作系统回收

  • 在c++中主要利用new在堆区开辟内存。

  1. #include<iostream>
  2. using namespace std;
  3. int* func() {
  4. //利用new关键字 可以将数据开辟到堆区
  5. //指针 本质也是局部变量,放在栈上,指针保存的数据放在堆区
  6. int* p = new int(10);
  7. return p;
  8. }
  9. int main() {
  10. //在堆区开辟数据
  11. int* p = func();
  12. cout << *p << endl; //10
  13. system("pause");
  14. return 0;
  15. }

  • ## 3.new操作符

  • c++中利用new操作符在堆区开辟数据

  • 堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符delete

  • 语法: new 数据类型

  • 利用new创建的数据,会返回该数据对应的类型的指针。

  1. #include<iostream>
  2. using namespace std;
  3. int* func() {
  4. //在堆区创建整型数据
  5. //new 返回是 该数据类型的指针
  6. int* a = new int(10);
  7. return a;
  8. }
  9. //2.在堆区利用new开辟数组
  10. void test02() {
  11. //创建10个整型数据的数组,在堆区
  12. int *p = new int[10];
  13. for (int i = 0; i < 10; i++) {
  14. p[i] = i + 100;
  15. }
  16. for (int i = 0; i < 10; i++) {
  17. cout << p[i] << endl;
  18. }
  19. //释放堆区数组
  20. //释放数组的时候 要加[] 才可以
  21. delete[]p;
  22. }
  23. int main() {
  24. int* p = func();
  25. cout << *p << endl;
  26. //如果想释放堆区的数据,利用关键词delete
  27. delete p;
  28. // cout << *p << endl;
  29. test02();
  30. system("pause");
  31. return 0;
  32. }

七 .引用

## 1 引用的基本使用

作用:给变量起别名

语法:数据类型 &别名 = 原名

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. //引用的基本语法
  5. //数据类型 &别名 = 原名
  6. int a = 10;
  7. int& b = a;
  8. cout << "a: " << a << endl; //10
  9. cout << "b: " << b << endl; //10
  10. b = 20;
  11. cout << "a: " << a << endl; //20
  12. cout << "b: " << b << endl; //20
  13. system("pause");
  14. return 0;
  15. }6-5

## 2.引用注意事项

.引用必须初始化

.引用在初始化后,不可以改变

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. int a = 10;
  5. int b = 20;
  6. //int &c; //错误,引用必须初始化
  7. int& c = a;// 一旦初始化后,就不更改
  8. c = b; //这是赋值操作,不是更改引用
  9. cout << "a=" << a << endl; //20
  10. cout << "b=" << b << endl; //20
  11. cout << "c=" << c << endl;//20
  12. system("pause");
  13. return 0;
  14. }

## 3.引用做函数参数

  • 作用:函数传递时,可以利用引用的技术让形参修饰实参

  • 优点:可以简化指针-修改实参

  1. #include<iostream>
  2. using namespace std;
  3. //值传递
  4. void mySwap01(int a,int b) {
  5. int temp = a;
  6. a = b;
  7. b = temp;
  8. }
  9. //地址传递
  10. void mySwap02(int* a, int* b) {
  11. int temp;
  12. temp = *a;
  13. *a = *b;
  14. *b = temp;
  15. }
  16. //引用传递
  17. void mySwap03(int& a, int& b) {
  18. int temp = a;
  19. a = b;
  20. b = temp;
  21. }
  22. int main() {
  23. int a = 10;
  24. int b = 20;
  25. mySwap01(a, b);
  26. cout << "a = " << a << endl; //10
  27. cout << "b = " << b << endl; //20
  28. mySwap02(&a, &b);
  29. cout << "a = " << a << endl; //20
  30. cout << "b = " << b << endl; //10
  31. mySwap03(a, b);
  32. cout << "a = " << a << endl; //10
  33. cout << "b = " << b << endl; //20
  34. system("pause");
  35. return 0;
  36. }

  • 总结: 通过引用参数产生的效果同按地址传递是一样。引用的语法更清楚简单。

## 4.引用做函数的返回值

  • 作用:引用是可以作为函数的返回存在的。

  • 注意:不要返回局部变量引用

  • 用法:函数调用作为左值

  1. #include<iostream>
  2. using namespace std;
  3. //不要返回局部变量的引用
  4. int& test01() {
  5. int a = 200; //局部变量 放在四区中的栈区
  6. return a;
  7. }
  8. // 函数的调用可以作为左值。
  9. int& test02() {
  10. static int a = 20; // 静态变量,存放在全局区,全局区上的数据在程序结束后系统释放
  11. return a;
  12. }
  13. int main() {
  14. int& ref = test01();
  15. cout << "ref = " << ref << endl; //-858993460 不要返回局部变量的引用
  16. int& ref2 = test02();
  17. cout << "ref2 = " << ref2 << endl; //20
  18. cout << "ref2 = " << ref2 << endl; //20
  19.     //如果函数的返回值是引用,这个函数调用可以作为左值
  20. test02() = 1000;
  21. cout << "ref2 = " << ref2 << endl; //1000
  22. cout << "ref2 = " << ref2 << endl; //1000
  23. system("pause");
  24. return 0;
  25. }

## 2.5引用的本质

  • 本质:引用的本质在c++内部实现是一个指针常量

  1. #include<iostream>
  2. using namespace std;
  3. // 发现是引用,转换为int* const ref = &a;
  4. void func(int &ref) {
  5. ref = 100; //ref 是引用,转换为*ref =100
  6. }
  7. int main() {
  8. int a = 10;
  9. //自动转换为:int*const ref =&a; 指针常量是指针指向不可改。也说明为什么引用不可更改
  10. int& ref = a;
  11. ref = 20; //内部发现ref 是引用,自动帮我们转换为:*ref =20;
  12. cout << "a: " << a << endl; //20
  13. cout << "ref: " << ref << endl; //20
  14. func(a);
  15. cout << "a: " << a << endl; //100
  16. cout << "ref: " << ref << endl; //100
  17. system("pause");
  18. return 0;
  19. }

## 2.6常量引用

  • 作用:常量引用主要用来修饰形参,防止误操作

  • 在函数形参中,可以加const 修饰形参,防止形参改变实参。

  1. #include<iostream>
  2. using namespace std;
  3. int main() {
  4. //常量引用
  5. //使用场景:用来修饰操作,防止误操作
  6. int a = 10;
  7. // int& ref = 10;// 引用必须引一块合法的内存空间
  8. const int& ref = 10;
  9. //ref = 10; //加入const 之后变为只读,不可以修改
  10. system("pause");
  11. return 0;
  12. }

八 .函数提高

  • ## 1.函数默认参数

  • 在c++中,函数的形参列表中的形参是可以有默认值的

  • 语法: 返回值类型 函数名 (参数 = 默认值){}

  • 注意事项:

  • 1. 如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须有默认值

  • 2.如果函数声明有默认参数,函数实现就不能有默认参数 声明和实现只能有一个有默认参数

  1. #include<iostream>
  2. using namespace std;
  3. //函数默认参数
  4. //语法: 返回值类型 函数名(形参 = 默认值)
  5. int func(int a,int b ,int c) {
  6. return a + b + c;
  7. }
  8. int func2(int a, int b = 10, int c = 20) {
  9. return a + b + c;
  10. }
  11. //注意事项:
  12. //1. 如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须有默认值
  13. //
  14. //int func3(int a, int b = 10, int c) { //报错
  15. // return a + b + c;
  16. //}
  17. //2.如果函数声明有默认参数,函数实现就不能有默认参数
  18. //声明和实现只能有一个有默认参数
  19. int func3(int a, int b); //声明函数
  20. int func3(int a, int b) {
  21. return a + b;
  22. }
  23. //int func4(int a=10, int b=10); //声明函数 //报错
  24. //int func4(int a=10, int b=10) {
  25. // return a + b;
  26. //}
  27. int func5(int a = 10, int b = 10);
  28. int func5(int a,int b) {
  29. return a + b;
  30. }
  31. int main() {
  32. int sum = func(10, 20, 30);
  33. cout << "sum = " << sum << endl; //60
  34. int sum1 = func2(10);
  35. cout << "sum1 = " << sum1 << endl; //40
  36. //如果我们自己传入了数据,就用自己的数据,如果没有,那么用默认值。
  37. int sum2 = func2(10,20);
  38. cout << "sum1 = " << sum2 << endl; //50
  39. //cout << func4(10, 10);
  40. cout << func5() << endl;
  41. system("pause");
  42. return 0;
  43. }

## 2.函数默认参数

  • c++ 中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置。

  • 语法: 返回值类型 函数名 (数据类型){}

  1. #include<iostream>
  2. using namespace std;
  3. //占位参数, 还可以有默认参数。
  4. void func(int a,int = 20) {
  5. cout << "this is func " << endl;
  6. }
  7. int main() {
  8. func(10);
  9. system("pause");
  10. return 0;
  11. }

## 3.函数重载

  • 函数重载概述

  • 作用: 函数名可以相同,提高复用性

  • 函数重载满足条件:

  • 同一个作用域下

  • 函数名称相同

  • 函数参数类型不同 或者 个数相同 或者 顺序不同

  • 注意: 函数的返回值不可以作为函数重载的条件

  1. #include<iostream>
  2. using namespace std;
  3. void chongzan() {
  4. cout << "chongzan" << endl;
  5. }
  6. //函数的返回值不可以作为函数重载的条件
  7. //int chongzan() {
  8. // cout << "chongzan" << endl;
  9. //}
  10. void chongzan(int a) {
  11. cout << "chongzan(int a)" << endl;
  12. }
  13. void chongzan(double a) {
  14. cout << "chongzan(double a)" << endl;
  15. }
  16. int main() {
  17. chongzan();
  18. chongzan(10);
  19. chongzan(10.0);
  20. system("pause");
  21. return 0;
  22. }

  • 函数重载注意事项

  • 引用作为重载条件

  • 函数重载到函数默认参数

  1. #include<iostream>
  2. using namespace std;
  3. //函数重载的注意事项
  4. //1.引用作为重载的条件
  5. void fun(int& a) {
  6. cout << "func() 调用" << endl;
  7. }
  8. void fun(const int& a) {
  9. cout << "func(const int& a) 调用" << endl;
  10. }
  11. //2.函数重载碰到默认参数
  12. void fun2(int a) {
  13. cout << "func2(int a) 的调用" << endl;
  14. }
  15. void fun2(int a,int b=10) {
  16. cout << "func2(int a,int b) 的调用" << endl;
  17. }
  18. int main() {
  19. int a = 10;
  20. fun(a); // 调用fun(int &a);
  21. fun(10); //调用fun(const int &a);
  22. //fun2(10); 当函数重载碰到默认参数,已经二义性,报错,尽量避免这种情况
  23. system("pause");
  24. return 0;
  25. }

九 .类和对象

  • c++面向对象的三大特性为: 封装、继承、多态

  • c++ 认为万事万物皆为对象,对象上有其属性和行为。

  • 例如:

  • 人可以作为对象,属性有姓名、年龄、身高、体重..., 行为有走、跑、跳、吃饭、唱歌。

  • 车也可以作为对象,属性有轮胎、方向盘、车灯、行为有载人、放音乐、放空调...

  • 具有相同性质的对象,我们可以抽象称为类,人属于人类,车属于车类。

##1. 封装

##1.1 封装的意义

封装是c++ 面向对象三大特性之一

封装的意义:

  • 将属性和行为作为一个整体,表现生活中的事物

  • 将属性和行为加以权限控制

  • 1.封装意义一:
  • 在设计类的时候,属性和行为写在一起,表现事物

语法: class 类名{访问权限:属性/行为};

  • //示例1:设计一个圆类,求圆的周长

  1. #include<iostream>
  2. using namespace std;
  3. //圆周率
  4. const double PI = 3.14;
  5. //设计一个圆类,求圆的周长
  6. //圆求周长的公式: 2*PI*半径
  7. class Circle {
  8. //访问权限
  9. //公共权限
  10. public:
  11. //属性(变量)
  12. double m_r; //半径
  13. //行为(函数)
  14. double calculateZC() { //获取圆的周长
  15. return 2 * PI * m_r;
  16. }
  17. double area() { //获取圆的面积
  18. return PI * m_r * m_r;
  19. }
  20. };
  21. int main() {
  22. // 通过圆类 创建具体的值(对象)
  23. Circle cl;
  24. cl.m_r = 10;
  25. cout << "圆的周长: = " << cl.calculateZC() << endl;
  26. cout << "圆的面积: = " << cl.area() << endl;
  27. system("pause");
  28. return 0;
  29. }

  • //示例2:设计一个学生类,属性有姓名和学号,可以给姓名和学号赋值,可以显示学生的姓名和学号

  • //类中的属性和行为 我们统一称为 成员

  • 属性 成员属性 成员变量

  • 行为 成员函数 成员方法

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Student {
  5. public: //公共权限
  6. //属性:
  7. string m_name;
  8. int m_id=0;
  9. //行为
  10. void setName(string name) {
  11. m_name = name;
  12. }
  13. void setId(int id) {
  14. m_id = id;
  15. }
  16. void showStudent() { //显示姓名和学号
  17. cout << "姓名: " << m_name << endl;
  18. cout << "学号: " << m_id << endl;
  19. }
  20. };
  21. int main() {
  22. Student stu;
  23. //stu.m_name = "张三";
  24. //stu.m_id = 1;
  25. stu.setName("张三");
  26. stu.setId(1);
  27. stu.showStudent();
  28. system("pause");
  29. return 0;
  30. }

  • 2.封装意义二:
  • 类在设计时,可以把属性和行为放在不同的权限下,加以控制

  • 访问权限有三种:

  • 1.public 公共权限

  • 2.protected 保护权限

  • 3.private 私有权限

  1. #include<iostream>
  2. using namespace std;
  3. //访问权限
  4. //三种
  5. //公共权限 public 成员 类内可以访问 类外可以访问
  6. //保护权限 protected 成员 类内可以访问 类外不可以访问 儿子可以访问父亲中的保护内容
  7. //私有权限 private 成员 类内可以访问 类外不可以访问 儿子不可以访问父亲的私有内容
  8. class Person {
  9. public:
  10. //公共权限
  11. string m_Name; // 姓名
  12. protected:
  13. //保护权限
  14. string m_Car; //汽车
  15. private:
  16. // 私有权限
  17. int m_Password=0; //银行卡密码
  18. public:
  19. void func() {
  20. m_Name = "张三";
  21. m_Car = "拖拉机";
  22. m_Password = 12234;
  23. cout << "m_car " << m_Car << endl;
  24. }
  25. };
  26. int main() {
  27. //实例化具体对象
  28. Person p1;
  29. p1.m_Name = "李四";
  30. //p1.m_car = "奔驰"; //保护权限内容,在类外访问不到;
  31. //p1.Password = 12234; //私有权限内容,在类外访问不到
  32. p1.func();
  33. system("pause");
  34. return 0;
  35. }

##1.2 struct 和class 区别

  • 在c++中struct 和class 唯一的区别就在于默认的访问权限。

  • 区别:

  • struct默认权限为公共 public

  • class默认权限为私有 private

  1. #include<iostream>
  2. using namespace std;
  3. class C1 {
  4. int m_A; //默认权限 是 私有
  5. };
  6. struct C2 {
  7. int m_A; // 默认权限 是 公共
  8. };
  9. int main() {
  10. C1 c1;
  11. //c1.m_A = 100; //在class里默认权限不可访问
  12. C2 c2;
  13. c2.m_A = 100; //在struct 默认的权限为公共,因此可以访问
  14. system("pause");
  15. return 0;
  16. }

## 1.3成员属性设置为私有

  • 优点1: 将所有成员属性设置为私有,可以自己控制读写权限

  • 优点2:对于写权限,我们可以检测数据的有效性。

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Per {
  5. public:
  6. //设置姓名
  7. void setName(string name) {
  8. m_Name = name;
  9. }
  10. //获取姓名
  11. string getName() {
  12. return m_Name;
  13. }
  14. //获取年龄
  15. int getAge() {
  16. return m_Age;
  17. }
  18. void setAge(int age) {
  19. if (age < 150 && age >= 0) {
  20. m_Age = age;
  21. }else {
  22. m_Age = 0;
  23. cout << "你这个老妖精: " << endl;
  24. return;
  25. }
  26. }
  27. // 设置情人
  28. void setLover(string Lover) {
  29. m_Lover = Lover;
  30. //cout << "m_Lover: " << m_Lover << endl;
  31. }
  32. private:
  33. //姓名 可读可写
  34. string m_Name;
  35. //年龄 只读
  36. int m_Age=0;
  37. //情人 只读
  38. string m_Lover;
  39. };
  40. int main() {
  41. Per p;
  42. p.setName("张三");
  43. string name = p.getName();
  44. cout << "姓名: " << name << endl;
  45. p.setAge(1000);
  46. int age = p.getAge();
  47. cout << "年龄: " << age << endl;
  48. p.setLover("tangcyp");
  49. system("pause");
  50. return 0;
  51. }

##1.4 案例: 设计立方体

  • 设计立方体类(Cube)

  • 求出立方体的面积和体积

  • 分别用全局函数和成员函数判断两个立方体是否相等。

  1. #include<iostream>
  2. using namespace std;
  3. class Cube {
  4. public:
  5. //设置长
  6. void setL(double L) {
  7. m_L = L;
  8. }
  9. //获取长
  10. double getL() {
  11. return m_L;
  12. }
  13. //设置宽
  14. void setW(double W) {
  15. m_W = W;
  16. }
  17. //获取宽
  18. double getW() {
  19. return m_W;
  20. }
  21. //设置高
  22. void setH(double H) {
  23. m_H = H;
  24. }
  25. //获取高
  26. double getH() {
  27. return m_H;
  28. }
  29. //求面积
  30. double Area() {
  31. return 2 * (m_L * m_W + m_W * m_H + m_L * m_H);
  32. }
  33. //求体积
  34. double volume() {
  35. return m_L * m_W * m_H;
  36. }
  37. //利用成员函数判断两个立方体是否相等
  38. bool isSameByClass(Cube& c) {
  39. if ((int)Area() == (int)c.Area() && (int)volume() == (int)c.volume()) {
  40. return true;
  41. }
  42. else {
  43. return false;
  44. }
  45. }
  46. private:
  47. //属性
  48. double m_L=0.0;
  49. double m_H=0.0;
  50. double m_W=0.0;
  51. };
  52. //利用全局函数判断 两个立方体是否相等
  53. //bool isSame(Cube & c1, Cube & c2) {
  54. // if ((int)c1.Area() == (int)c2.Area() && (int)c1.volume() == (int)c2.volume() ) {
  55. // return true;
  56. // }
  57. // return false;
  58. //}
  59. int main() {
  60. Cube c1;
  61. c1.setL(10.4); //长
  62. c1.setW(1.4); //宽
  63. c1.setH(10.2); //高
  64. //cout << c1.Area() << endl; //面积
  65. //cout << c1.volume() << endl; //体积
  66. Cube c2;
  67. c2.setL(10.4); //长
  68. c2.setW(10.2); //宽
  69. c2.setH(1.4); //高
  70. //bool ret = isSame(c1, c2);
  71. bool ret = c1.isSameByClass(c2);
  72. if (ret) {
  73. cout << "c1和c2是相等的 " << endl;
  74. }
  75. else {
  76. cout << "c1和c2不是相等的 " << endl;
  77. }
  78. system("pause");
  79. return 0;
  80. }

##1.5 案例: 点和圆的关系

  • 设计一个圆形类(Circle),和一个点(Point),计算点到圆的关系

  1. //Cricle.h文件
  2. #pragma once
  3. #include<iostream>
  4. #include "point.h"
  5. using namespace std;
  6. //圆类
  7. class Circle {
  8. public:
  9. //设置半径
  10. void setR(int r);
  11. //获取半径
  12. int getR();
  13. //设置圆心
  14. void setCenter(Point center);
  15. //获取圆心
  16. Point getCenter();
  17. private:
  18. int m_R = 0; //半径
  19. //在类中可以让另一个类 作为本类中的成员
  20. Point m_Center; //圆心
  21. };
  1. //Cricle.cpp文件
  2. #include "Circle.h"
  3. //设置半径
  4. void Circle::setR(int r) {
  5. m_R = r;
  6. }
  7. //获取半径
  8. int Circle::getR() {
  9. return m_R;
  10. }
  11. //设置圆心
  12. void Circle::setCenter(Point center) {
  13. m_Center = center;
  14. }
  15. //获取圆心
  16. Point Circle::getCenter() {
  17. return m_Center;
  18. }
  1. //ppoint.h文件
  2. #pragma once
  3. #include<iostream>
  4. using namespace std;
  5. //点类
  6. class Point {
  7. public:
  8. //设置X
  9. void setX(int x);
  10. //获取X
  11. int getX();
  12. //设置Y
  13. void setY(int y);
  14. //获取Y
  15. int getY();
  16. private:
  17. int m_X = 0; //x
  18. int m_Y = 0; //y
  19. };
  1. //point.cpp文件
  2. #include "point.h"
  3. //设置X
  4. void Point::setX(int x) {
  5. m_X = x;
  6. }
  7. //获取X
  8. int Point::getX() {
  9. return m_X;
  10. }
  11. //设置Y
  12. void Point::setY(int y) {
  13. m_Y = y;
  14. }
  15. //获取Y
  16. int Point::getY() {
  17. return m_Y;
  18. }
  1. //main文件
  2. #include<iostream>
  3. #include"Circle.h"
  4. using namespace std;
  5. void isInCircle(Circle& c, Point& p) {
  6. //计算两点之间距离 平方
  7. int distance = pow(c.getCenter().getX() - p.getX(), 2) + pow(c.getCenter().getY() - p.getY(), 2);
  8. //计算半径的平方
  9. int rDistance = c.getR()*c.getR();
  10. //判断关系
  11. if (distance == rDistance) {
  12. cout << "点在圆上" << endl;
  13. }
  14. else if (distance > rDistance) {
  15. cout << "点在圆外" << endl;
  16. }
  17. else {
  18. cout << "点在圆内" << endl;
  19. }
  20. }
  21. int main() {
  22. Point po;
  23. po.setX(10);
  24. po.setY(11);
  25. Point center;
  26. center.setX(10);
  27. center.setY(0);
  28. Circle c1;
  29. c1.setR(10);
  30. c1.setCenter(center);
  31. isInCircle(c1, po);
  32. system("pause");
  33. return 0;
  34. }

##2.对象的初始化和清理

  • 生活中我们买的电子产品都基本会有出厂设置,在某一天我们不用的时候删除一些自己信息数据保证安全。

  • C++中的面向对象来源于生活,每个对象也都有初始设置以及对象销毁前的清理数据的设置。

## 2.1构造函数和析构函数

  • 对象的初始化和清理也是两个非常重要的安全问题

  • 一个对象或者变量没有初始状态,对其使用后果是未知

  • 同时的使用完一个对象或变量,没有及时清理,也会造成一定的安全问题

  • c++ 利用了构造函数和析构函数解决上述问题,这两个函数将会被编译器自动调用,完成对象初始化和清理工作。对象的初始化和清理工作是编译器强制要我们做的事情,因此如果我们不提供构造和析构,编译器会提供。编译器提供的构造函数和析构函数是空实现

  • 构造函数:主要作用于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。

  • 析构函数:主要作用于对象销毁前 系统自动调用,执行一些清理工作。

  • 构造函数语法: 类名(){}

  • 1.构造函数,没有返回值也不写void

  • 2.函数名称与类名相同

  • 3.构造函数可以有参数,因此可以发生重载

  • 4.程序在调用对象时候会自动调用构造,无须手动调用,而且只会调用一次。

  • 析构函数语法:~ 类名(){}

  • 1.析构函数,没有返回值也不写void

  • 2.函数名称与类名相同,在名称前加上符号~

  • 3.析构函数不可以有参数,因此不可以发生重载

  • 4.程序在调用对象时候会自动调用析构,无须手动调用,而且只会调用一次。

  1. #include<iostream>
  2. using namespace std;
  3. //对象的初始化和清理
  4. class Person {
  5. public:
  6. //1.构造函数 进行初始化操作
  7. Person() {
  8. cout << "Person 构造函数的调用" << endl;
  9. }
  10. //2.析构函数 进行清理的操作
  11. ~Person() {
  12. cout << "~Person 析构函数的调用" << endl;
  13. }
  14. };
  15. void test01() {
  16. Person p; //在栈上的数据,test01执行完毕后,释放这个对象
  17. }
  18. int main() {
  19. test01();
  20. //Person p;
  21. system("pause");
  22. return 0;
  23. }

## 2.2构造函数的分类及调用

  • 两种分类方式:

  • 按参数分为:有参构造和无参构造(默认构造)

  • 按类型分为:普通构造和拷贝构造

  • 三种调用方式:

  • 括号法

  • 显示法

  • 隐式转换法

  1. #include<iostream>
  2. using namespace std;
  3. //构造函数的分类即调用
  4. //分类
  5. class Per {
  6. //构造函数
  7. public:
  8. //无参构造(默认构造)
  9. Per() {
  10. cout << "Person的无参构造函数调用" << endl;
  11. }
  12. //有参构造
  13. Per(int a) {
  14. age = a;
  15. cout << "Person的有参构造函数调用" << endl;
  16. }
  17. //拷贝构造函数
  18. Per(const Per &p) {
  19. //将传入的人身上的属性,拷贝到我身上。
  20. age = p.age;
  21. cout << "Person的拷贝构造函数调用" << endl;
  22. }
  23. ~Per() {
  24. cout << "Person的析构函数调用" << endl;
  25. }
  26. int age=0;
  27. };
  28. void test02() {
  29. //括号法:
  30. //Per p; //默认构造函数调用
  31. //Per p1(10); // 有参构造函数
  32. //Per p2(p1);// 拷贝构造函数
  33. //注意事项1
  34. // 调用默认构造函数时候,不要加()
  35. // 因为下面这行代码,编译器会认为是一个函数的声明,不会认为是在创建对象
  36. //Per p();
  37. //cout << "p1的年龄为: " << p1.age << endl;
  38. //cout << "p2的年龄为: " << p2.age << endl;
  39. //显示法
  40. //Per p1;
  41. //Per p2 = Per(10); //有参构造 Per(10);// 匿名对象 特点:当前执行结束后,系统会立即回收掉匿名对象。
  42. //Per p3 = Per(p2); //拷贝构造
  43. //注意事项2
  44. //不要利用拷贝构造函数 初始化匿名对象
  45. //Per(p3); //重定义报错 编译器会认为Per(p3) === Per p3; 对象声明
  46. //隐式转换法
  47. //Per p1;
  48. //Per p2 = 10; //有参构造 相当于写了 Per p2 = Per(10);
  49. //Per p3 = p2; // 拷贝构造 Per p3 = Per(p2);
  50. }
  51. int main() {
  52. test02();
  53. system("pause");
  54. return 0;
  55. }

## 2.3拷贝构造函数的调用时机

  • c++中构造函数的调用时机通常有三种情况

  • 使用一个已经创建完毕的对象来初始化一个新对象。

  • 值传递的方式给函数参数传值

  • 以值方式返回局部对象

  1. #include<iostream>
  2. using namespace std;
  3. class Person {
  4. public:
  5. //默认构造
  6. Person() {
  7. cout << "Person默认构造函数调用 " << endl;
  8. }
  9. Person(int age) {
  10. cout << "Person有参构造函数调用 " << endl;
  11. m_Age = age;
  12. }
  13. //拷贝函数
  14. Person(const Person& p) {
  15. cout << "Person拷贝构造函数调用 " << endl;
  16. m_Age = p.m_Age;
  17. }
  18. //析构函数
  19. ~Person() {
  20. cout << "Person析构构造函数调用 " << endl;
  21. }
  22. int m_Age=0;
  23. };
  24. //拷贝构造函数调用时机
  25. //1.使用一个已经创建完毕的对象来初始化一个新对象
  26. void test03() {
  27. Person p1(20);
  28. Person p2(p1);
  29. cout << "p1的年龄为: " << p1.m_Age << endl;
  30. cout << "p2的年龄为: " << p2.m_Age << endl;
  31. }
  32. //2.值传递的方式给函数参数传值
  33. void doWork(Person p) {
  34. }
  35. void test04() {
  36. Person p;
  37. doWork(p); //会调用拷贝构造函数
  38. }
  39. //3.值方式返回局部对象
  40. Person doWork2() {
  41. Person p1;
  42. cout << (int*)&p1 << endl; //000000E5F7AFF844
  43. return p1; //会调用拷贝构造函数
  44. }
  45. void test05() {
  46. Person p = doWork2(); ///Person p = p1;
  47. cout << (int*)&p << endl; //000000E5F7AFF984
  48. }
  49. int main() {
  50. //test03();
  51. //test04();
  52. test05();
  53. system("pause");
  54. return 0;
  55. }

## 2.4 构造函数调用规则

  • 默认情况下,c++编译器至少给一个类添加3个函数

  • 默认构造函数(无参,函数体为空)

  • 默认析构函数(无参,函数体为空)

  • 默认拷贝构造函数,对属性进行值拷贝

  • 构造函数调用规则如下:

  • 如果用户定义有参数构造函数,c++不在提供默认无参构造,但是会提供默认拷贝构造

  • 如果用户定义拷贝构造函数,c++不会再提供其他构造函数。

  • 拷贝构造函数 > 有参构造函数 > 无参构造函数

  1. #include<iostream>
  2. using namespace std;
  3. class Person {
  4. public:
  5. //Person() {
  6. // cout << "Person的默认构造函数构造 " << endl;
  7. //}
  8. //Person(int age) {
  9. // cout << "Person的有参构造函数构造 " << endl;
  10. // m_Age = age;
  11. //}
  12. Person(const Person& p) {
  13. cout << "Person的拷贝构造函数构造 " << endl;
  14. m_Age = p.m_Age;
  15. }
  16. ~Person() {
  17. cout << "Person的默认析构函数构造 " << endl;
  18. }
  19. int m_Age=0;
  20. };
  21. //void test06() {
  22. // Person p;
  23. // p.m_Age = 18;
  24. // Person p2(p);
  25. // cout << "p2的年龄为: " << p2.m_Age << endl;
  26. //}
  27. void test07() {
  28. //Person p; //如果用户定义有参数构造函数,c++不在提供默认无参构造,但是会提供默认拷贝构造
  29. //Person p(10);
  30. //Person p1(p);//由于用户没有定义拷贝构造函数,会调用编译器添加的默认拷贝构造函数
  31. //cout << "p1的年龄为: " << p1.m_Age << endl; //10
  32. }
  33. int main() {
  34. //test06();
  35. test07();
  36. system("pause");
  37. return 0;
  38. }

## 2.5 深拷贝与浅拷贝

  • 深浅拷贝是面试经典问题,也是常见的一个坑

  • 浅拷贝:简单的赋值拷贝操作

  • 深拷贝:在堆区重新申请空间,进行拷贝操作

  1. #include<iostream>
  2. using namespace std;
  3. //深拷贝与浅拷贝
  4. class Person1 {
  5. public:
  6. Person1() {
  7. cout << "Person的默认构造函数的调用" << endl;
  8. }
  9. Person1(int age,int height) {
  10. m_Height = new int(height); //new 返回是 该数据类型的指针
  11. m_age1 = age;
  12. cout << "Person的有参构造函数的调用" << endl;
  13. }
  14. //自己实现一个拷贝构造函数,解决浅拷贝带来的问题
  15. Person1(const Person1& p) {
  16. cout << "Perosn拷贝构造函数调用 " << endl;
  17. m_age1 = p.m_age1;
  18. //m_Height = p.m_Height; //编译器默认实现的就是这行代码
  19. //深拷贝操作
  20. m_Height = new int(*p.m_Height);
  21. }
  22. ~Person1() {
  23. //析构代码,将堆区开辟数据做释放操作
  24. if (m_Height != NULL) {
  25. delete m_Height;
  26. m_Height = NULL;
  27. }
  28. cout << "Person的析构函数的调用" << endl;
  29. }
  30. int m_age1 = 0;
  31. int *m_Height = 0;
  32. };
  33. void test10() {
  34. //浅拷贝带来的问题是堆区的内存重复释放(利用深拷贝进行解决)
  35. //堆栈数据的进出原则是先进后出;其中栈是一种数据结构,
  36. //它按照先进后出的原则存储数据,先进入的数据被压入栈底,
  37. //最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据。
  38. Person1 p5(10,160);
  39. cout << "p5的年龄为: " << p5.m_age1 << endl;
  40. cout << "p5的身高为: " << *p5.m_Height << endl;
  41. Person1 p6(p5);
  42. cout << "p6的年龄为: " << p6.m_age1 << endl;
  43. cout << "p6的身高为: " << *p6.m_Height << endl;
  44. }
  45. int main() {
  46. test10();
  47. system("pause");
  48. return 0;
  49. }
  • 总结: 如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题。

## 2.6 初始化列表

  • 作用:c++提供了初始化列表语法,用来初始化属性

  • 语法: 构造函数():属性1(值1),属性2(值2)...{}

  • 在C++中,对象的成员变量可以使用初始化列表进行初始化,也可以在构造函数中使用传统方式进行初始化。

  • 使用初始化列表可以在构造函数被调用之前对成员变量进行初始化。这种方式可以更方便的初始化const变量,以及具有复杂类型的成员变量(比如指针、数组等)。同时,初始化列表还可以同时初始化多个成员变量,在代码的可读性和效率上都更好。

  • 使用传统的初始化方式可以在构造函数中进行更多的逻辑处理。可以根据需要在其内部进行一些初始化的操作,比如读取文件、计算等等。

  • 两种初始化方式各有优劣,可以根据情况选择使用。但现代C++编程更倾向于使用初始化列表来初始化成员变量,因为它可以提高代码的可读性和效率,同时可以避免一些错误。

  1. #include<iostream>
  2. using namespace std;
  3. class Person2 {
  4. public :
  5. // 传统初始化操作
  6. //Person(int a,int b,int c) {
  7. // m_A = a;
  8. // m_B = b;
  9. // m_C = c;
  10. // cout << "Person的有参构造函数的调用 " << endl;
  11. //}
  12. // 初始化列表进行初始化属性
  13. Person2(int a,int b,int c) : m_A(a), m_B(b), m_C(c) {
  14. }
  15. int m_A;
  16. int m_B;
  17. int m_C;
  18. };
  19. void test11() {
  20. //Person p1(1, 2, 3);
  21. Person2 p3(10,20,30);
  22. cout << "m_A = " << p3.m_A << endl;
  23. cout << "m_B = " << p3.m_B << endl;
  24. cout << "m_C = " << p3.m_C << endl;
  25. }
  26. int main() {
  27. test11();
  28. system("pause");
  29. return 0;
  30. }

## 2.7 类对象作为类成员

  • c++ 类中的成员可以是另一个类的对象,我们称该成员为对象成员。

  1. class A{}
  2. class B{
  3.     A a;
  4. }
  • B类中有对象作为成员,A为对象成员

  • 那么当创建B对象时,A与B的构造和析构的顺序是谁先谁后?

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //类对象作为类成员
  5. class Phone {
  6. public:
  7. //利用初始化列表进行初始化属性
  8. Phone(string pName) :m_PName(pName) {
  9. cout << "Phone的构造函数的调用" << endl;
  10. }
  11. ~Phone() {
  12. cout << "Phone析构函数的调用" << endl;
  13. }
  14. string m_PName;
  15. };
  16. class Person4 {
  17. public:
  18. // Phone m_phone = PName //隐式转换
  19. Person4(string name, string PName) : m_Name(name), m_Phone(PName) {
  20. cout << "Person4的构造函数的调用" << endl;
  21. }
  22. ~Person4() {
  23. cout << "Perosn4析构函数的调用" << endl;
  24. }
  25. //姓名
  26. string m_Name;
  27. //手机
  28. Phone m_Phone;
  29. };
  30. //当其他类对象作为本类成员,构造时候 ,先构造其他类对象,再构造自身
  31. //当其他类对象作为本类成员,析构时候 ,先析构自身,再析构其他类对象
  32. void test12() {
  33. Person4 p("张三", "三星");
  34. cout << "姓名 " << p.m_Name << endl; //姓名
  35. cout << "手机品牌 " << p.m_Phone.m_PName << endl; //手机品牌
  36. }
  37. int main() {
  38. test12();
  39. system("pause");
  40. return 0;
  41. }
  42. //运行结果:
  43. //Phone的构造函数的调用
  44. //Person4的构造函数的调用
  45. //姓名 张三
  46. //手机品牌 三星
  47. //Perosn4析构函数的调用
  48. //Phone析构函数的调用

## 2.8 静态成员

  • 静态成员就是在成员变量和成员函数加上关键词static,称为静态成员

  • 静态成员:

  • 静态成员变量

  • 所有对象共享同一份数据

  • 在编译阶段分配内存

  • 类内声明、类外初始化

  • 静态成员函数

  • 所有对象共享同一个函数

  • 静态成员函数只能访问静态成员变量

  • 静态成员变量

  1. #include<iostream>
  2. using namespace std;
  3. //静态成员变量
  4. class Person5 {
  5. public:
  6. //▪ 所有对象共享同一份数据
  7. //▪ 在编译阶段分配内存
  8. // 类内声明、类外初始化
  9. //类内声明
  10. static int m_A;
  11. // 静态成员变量也是有访问权限的
  12. private:
  13. static int m_B;
  14. };
  15. //类外初始化
  16. int Person5::m_A = 100;
  17. int Person5::m_B = 200;
  18. void test14() {
  19. Person5 p;
  20. cout << p.m_A << endl; //100
  21. Person5 p2;
  22. p2.m_A = 200;
  23. cout << p2.m_A << endl; //200
  24. cout << p.m_A << endl; //200
  25. }
  26. void test15() {
  27. //静态成员变量 不属于某个对象上, 所有对象都共享同一份数据
  28. //因此静态成员变量有两种访问方式
  29. //1.通过对象进行访问
  30. Person5 p;
  31. cout << p.m_A << endl;
  32. //2.通过类名进行访问
  33. cout << Person5::m_A << endl;
  34. //cout << Person5::m_B << endl; //类外访问不到私有的静态成员变量
  35. }
  36. int main() {
  37. //test14();
  38. cout << "--------------" << endl;
  39. test15();
  40. system("pause");
  41. return 0;
  42. }
  • 静态成员函数:

  1. #include<iostream>
  2. using namespace std;
  3. //静态成员函数
  4. //所有对象共享同一个函数
  5. //静态成员函数只能访问静态成员变量
  6. class Person {
  7. public:
  8. //静态成员函数
  9. static void func() {
  10. //m_B = 0;// 静态成员函数不可以访问 非静态成员变量,无法区别到底是那个对象的m_B属性
  11. m_A = 100; //静态成员函数可以访问 静态成员变量
  12. cout << "static void func调用" << endl;
  13. }
  14. //静态成员变量
  15. static int m_A;
  16. int m_B=0;
  17. //静态成员函数也是有访问权限的
  18. private:
  19. static void func2() {
  20. cout << "static void func2调用" << endl;
  21. }
  22. };
  23. //类外初始化
  24. int Person::m_A = 0;
  25. void test16() {
  26. //1.通过对象访问
  27. Person p;
  28. p.func();
  29. //2.通过类名访问
  30. Person::func();
  31. //Person::func2(); 类外访问不到私有静态成员函数
  32. }
  33. int main() {
  34. test16();
  35. system("pause");
  36. return 0;
  37. }

##3.c++对象模型和this指针

## 3.1 成员变量和成员函数分开存储

  • 在c++中,类内的成员变量和成员函数分开存储

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

  1. #include<iostream>
  2. using namespace std;
  3. //成员变量和成员函数分开存储
  4. class Person {
  5. int m_A; //非静态成员变量 属于类的对象上
  6. static int m_B; //静态成员变量 不属于类对象上
  7. void func(){} //非静态成员函数 不属于类对象上
  8. static void func2() {} //静态成员函数 不属于类对象上
  9. };
  10. int Person::m_B = 0;
  11. //void test01() {
  12. // Person p;
  13. //空对象占用的内存空间为1
  14. //c++编译器会把每个空对象也分配一个字节空间,是为了区分空对象占内存的位置。
  15. //每个空对象也应该有一个独一无二的内存地址。
  16. // cout << "sizeof p = " << sizeof(p) << endl;
  17. //}
  18. void test02() {
  19. Person p;
  20. cout << "sizeof p = " << sizeof(p) << endl; //4
  21. }
  22. int main() {
  23. //test01();
  24. test02();
  25. system("pause");
  26. return 0;
  27. }

## 3.2this指针概念

  • 通过3.1我们知道在c++中成员变量和成员函数是分开存储的。

  • 每一个非静态成员函数只会诞生一份函数实例。也就是说多个同类型的对象会公用一块代码。

  • 那些问题是:这一块代码是如何区分那个对象调用自己的呢?

  • c++ 通过提供特殊的对象指针,this指针,解决上述问题this指针指向被调用的成员函数所属的对象。

  • this指针是隐含每一个非静态成员函数内的一种指针。

  • this指针不需要定义。直接使用即可。

  • this指针的用途:

  • 当形参和成员变量同名时,可用this指针来区分

  • 在类的非静态成员函数中返回对象,可使用return *this.

  1. #include<iostream>
  2. using namespace std;
  3. class Person {
  4. public:
  5. //1.解决名称冲突
  6. Person(int age) {
  7. //this指针指向 被调用的成员函数 所属的对象。
  8. this-> age = age;
  9. }
  10. Person& PersonAddAge(Person& p) {
  11. this->age += p.age;
  12. //this指向p2的指针,而*this指向的就是p2这个对象本体
  13. return *this;
  14. }
  15. int age;
  16. };
  17. //2.返回对象本身用*this
  18. void test04() {
  19. Person p1(10);
  20. Person p2(10);
  21. //链式编程思想
  22. p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
  23. cout << "p2的年龄为: " << p2.age << endl; //40
  24. }
  25. void test03() {
  26. Person p1(18);
  27. cout << "p1的年龄为: " << p1.age << endl; //18
  28. }
  29. int main() {
  30. test03();
  31. test04();
  32. system("pause");
  33. return 0;
  34. }

9.9.3 空指针访问成员函数

C++ 中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针。

如果用到this指针,需要加以判断保证代码的健壮性。

  1. #include<iostream>
  2. using namespace std;
  3. // 空指针调用成员函数
  4. class Person {
  5. public:
  6. void showClassName() {
  7. cout << "this is Person class" << endl;
  8. }
  9. void showClassAge() {
  10. //报错原因是因为传入的指针为NULL
  11. if (this == NULL) {
  12. return; // 提高代码的健壮性
  13. }
  14. cout << "Age = "<< m_Age << endl;
  15. }
  16. int m_Age;
  17. };
  18. void test05() {
  19. Person* p = NULL;
  20. p->showClassAge();
  21. p->showClassName();
  22. }
  23. int main() {
  24. test05();
  25. system("pause");
  26. return 0;
  27. }

9.3.4 const修饰成员函数

常函数:

成员函数后加const 后我们称为这个函数为常函数。

常函数内不可以修改成员属性。

成员属性声明时加关键字mutable后,在常函数中依然可以修改。

常对象:

声明对象前加const称该对象为常对象

常对象只能调用常函数

  1. #include<iostream>
  2. using namespace std;
  3. // 常函数
  4. class Person {
  5. public:
  6. //this指针的本质 是指针常量 指针常量的指向是不可以修改的
  7. //在成员函数后面加const,修饰的是this指向, 让指针指向的值也不可以修改。
  8. void showPerson() const{
  9. //this->m_A = 100;
  10. this->m_B = 100;
  11. }
  12. int m_A;
  13. mutable int m_B; // 特殊变量,即使在常函数中,也可以修改这个值, 加关键词mutable
  14. };
  15. void test06() {
  16. Person p;
  17. }
  18. void test07() {
  19. // 常对象
  20. const Person p1; //在对象前加const ,变为常对象
  21. p1.m_B = 100;
  22. p1.showPerson(); // 常对象只能调用常函数
  23. }
  24. int main() {
  25. test07();
  26. test06();
  27. system("pause");
  28. return 0;
  29. }

9.4友元

在程序中,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术

友元的目的就是让一个函数或者类访问另一个类中私有成员。

友元的关键词为friend

友元的三种实现

  • 全局函数做友元

  • 类做友元

  • 成员函数做友元

  1. // 全局函数做友元
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. class Building { // 房屋类
  6. friend void goodGay(Building* building);
  7. public:
  8. Building() {
  9. m_SittingRoom = "客厅";
  10. m_BedRoom = "卧室";
  11. }
  12. string m_SittingRoom;// 客厅
  13. private:
  14. string m_BedRoom; //卧室
  15. };
  16. // 全局函数
  17. void goodGay(Building* building) {
  18. cout << "好基友全局函数正在访问: " << building->m_SittingRoom << endl;
  19. cout << "好基友全局函数正在访问: " << building->m_BedRoom << endl;
  20. }
  21. void test01() {
  22. Building building;
  23. goodGay(&building);
  24. }
  25. int main() {
  26. test01();
  27. system("pause");
  28. return 0;
  29. }
  1. //类做友元
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #include<iostream>
  4. using namespace std;
  5. //类做友元
  6. class Building;
  7. class GoodGay {
  8. public:
  9. GoodGay();
  10. void visit(); //参观函数 访问Building中的属性
  11. Building* building;
  12. };
  13. class Building {
  14. friend class GoodGay; // GoodGay类是本来的好朋友,可以访问本类中私有的成员
  15. public:
  16. Building();
  17. string m_SittingRoom;// 客厅
  18. private:
  19. string m_BedRoom; //卧室
  20. };
  21. //类外写成员函数
  22. Building::Building() {
  23. m_SittingRoom = "客厅";
  24. m_BedRoom = "卧室";
  25. }
  26. GoodGay::GoodGay() {
  27. //创建建筑物对象
  28. building = new Building;
  29. }
  30. void GoodGay::visit() {
  31. cout << "好基友类正在访问: " << building->m_SittingRoom << endl;
  32. cout << "好基友类正在访问: " << building->m_BedRoom << endl;
  33. }
  34. void test09() {
  35. GoodGay gg;
  36. gg.visit();
  37. }
  38. int main() {
  39. test09();
  40. system("pause");
  41. return 0;
  42. }
  1. //成员函数做友元
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #include<iostream>
  4. #include<string>
  5. using namespace std;
  6. class Building;
  7. class GoodGay {
  8. public:
  9. GoodGay();
  10. void visit(); // 让visit函数可以访问Building中私有成员
  11. void visit2();// 让visit函数不可以访问Building中私有成员
  12. Building* building;
  13. };
  14. class Building {
  15. friend void GoodGay::visit();
  16. public:
  17. Building() { // 构造函数
  18. m_SittingRoom = "客厅";
  19. m_BedRoom = "卧室";
  20. }
  21. string m_SittingRoom; // 客厅
  22. private:
  23. string m_BedRoom; // 卧室
  24. };
  25. //类外实现成员函数
  26. GoodGay::GoodGay() {
  27. building = new Building;
  28. }
  29. void GoodGay::visit() {
  30. cout << "visit函数正在访问: " << building->m_SittingRoom << endl;
  31. cout << "visit函数正在访问: " << building->m_BedRoom << endl;
  32. }
  33. void GoodGay::visit2() {
  34. cout << "visit函数正在访问: " << building->m_SittingRoom << endl;
  35. //cout << "visit函数正在访问: " << building->m_BedRoom << endl;
  36. }
  37. void test10() {
  38. GoodGay gg;
  39. gg.visit();
  40. gg.visit2();
  41. }
  42. int main() {
  43. test10();
  44. system("pause");
  45. return 0;
  46. }

9.5 运算符重载

运算符重载的概念: 对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

9.5.1 加号运算符重载

作用:实现两个自定义数据类型相加的运算

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. class Person {
  6. public:
  7. // 1.成员函数重载+号
  8. //Person operator+(Person& p) {
  9. // Person temp;
  10. // temp.m_A = this->m_A + p.m_A;
  11. // temp.m_B = this->m_B + p.m_B;
  12. // return temp;
  13. //}
  14. int m_A;
  15. int m_B;
  16. };
  17. //2.全局函数重载+号
  18. Person operator+(Person &p1, Person &p2) {
  19. Person temp;
  20. temp.m_B = p1.m_B + p2.m_B;
  21. temp.m_A = p1.m_A + p2.m_A;
  22. return temp;
  23. }
  24. Person operator+(Person& p1, int num) {
  25. Person temp;
  26. temp.m_B = p1.m_B + num;
  27. temp.m_A = p1.m_A;
  28. return temp;
  29. }
  30. void test01() {
  31. Person p1;
  32. p1.m_A = 10;
  33. p1.m_B = 10;
  34. Person p2;
  35. p2.m_A = 10;
  36. p2.m_B = 10;
  37. Person p3 = p1 + p2;
  38. //成员函数重载本质调用
  39. //Person p3 = p1.operator+(p2);
  40. //全局函数重载本质调用
  41. //Person p3 = p1.operator+(p2,p1);
  42. //运算符重载也可以发生函数重载
  43. Person p4 = p1 + 10; // Person operator+(Person& p1, int num)
  44. cout << "p3.m_A = " << p3.m_A << endl;
  45. cout << "p3.m_B = " << p3.m_B << endl;
  46. cout << "p4.m_A = " << p4.m_A << endl;
  47. cout << "p4.m_B = " << p4.m_B << endl;
  48. }
  49. int main() {
  50. test01();
  51. system("pause");
  52. return 0;
  53. }

9.5.2 左移运算符重载

作用:可以输出自定义数据类型

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 左移运算符重载
  6. class Person {
  7. friend ostream& operator<<(ostream& cout, Person& p);
  8. public:
  9. Person(int a, int b) {
  10. this->m_A = a;
  11. this->m_B = b;
  12. }
  13. private:
  14. // 1.利用成员函数重载左移运算符 p.operator 简化版本p<<cout
  15. // 不会利用成员函数重载<< 运算符, 因为无法实现cout 在左侧
  16. //void operator<<(cout) {
  17. //
  18. //}
  19. int m_A;
  20. int m_B;
  21. };
  22. //只能利用全局函数重载左移运算符
  23. ostream & operator<<(ostream &cout, Person& p) {
  24. cout << "m_A = " << p.m_A << " m_B = " << p.m_B ;
  25. return cout;
  26. }
  27. void test02() {
  28. Person p(10,10);
  29. //cout << p.m_A << endl;
  30. cout << p << endl;
  31. }
  32. int main() {
  33. test02();
  34. system("pause");
  35. return 0;
  36. }

9.5.3 递增运算符重载

通过重载运算符,实现自己的整型数据

总结: 前置递增返回引用,后置递增返回值

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 重载递增运算符
  6. class MyInteger {
  7. friend ostream& operator<<(ostream& cout, MyInteger myint);
  8. public:
  9. MyInteger() {
  10. m_Num = 0;
  11. }
  12. // 重载前置++运算符
  13. MyInteger& operator++() {
  14. this->m_Num++;
  15. return *this;
  16. }
  17. // 重载后置++运算符
  18. //void operator++(int) int代表展位参数,可以用于区分前置和后置递增
  19. MyInteger operator++(int) {
  20. MyInteger temp = *this;
  21. this->m_Num++;
  22. return temp;
  23. }
  24. private:
  25. int m_Num;
  26. };
  27. ostream& operator<<(ostream& cout, MyInteger myint) {
  28. cout << myint.m_Num;
  29. return cout;
  30. }
  31. void test03() {
  32. MyInteger myint;
  33. cout << ++(++myint) << endl;
  34. cout <<myint << endl;
  35. }
  36. void test04() {
  37. MyInteger myint;
  38. cout << (myint++)++ << endl; //0
  39. cout << myint << endl;//1
  40. }
  41. int main() {
  42. test03();
  43. test04();
  44. system("pause");
  45. return 0;
  46. }

9.5.4 赋值运算符重载

c++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)

  1. 默认析构函数(无参,函数体为空)

  1. 默认拷贝构造函数,对属性进行值拷贝

  1. 赋值运算符operator=, 对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作也会出现深浅拷贝问题。

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. class Person {
  6. public:
  7. Person(int age) {
  8. m_Age = new int(age);
  9. }
  10. ~Person() {
  11. if (m_Age != NULL) {
  12. delete m_Age;
  13. m_Age = NULL;
  14. }
  15. }
  16. // 重载赋值运算符
  17. Person& operator=(Person& p) {
  18. //编译器是提供的浅拷贝
  19. // m_Age = p.m_Age
  20. //应该先判断是否有属性在堆区,如果有先释放干净,然后在深拷贝
  21. if (m_Age != NULL) {
  22. delete m_Age;
  23. m_Age = NULL;
  24. }
  25. // 深拷贝
  26. m_Age = new int(*p.m_Age);
  27. return *this;
  28. }
  29. int* m_Age;
  30. };
  31. void test05() {
  32. Person p1(18);
  33. cout << "p1的年龄为: " << *p1.m_Age << endl;
  34. Person p2(20);
  35. Person p3(30);
  36. p3 = p2 = p1; //赋值操作
  37. cout << "p2的年龄为: " << *p2.m_Age << endl;
  38. cout << "p3的年龄为: " << *p3.m_Age << endl;
  39. }
  40. int main() {
  41. test05();
  42. int a = 10;
  43. int b = 20;
  44. int c = 30;
  45. c = b = a;
  46. cout << "a=" << a << endl;
  47. cout << "b=" << b << endl;
  48. cout << "c=" << c << endl;
  49. system("pause");
  50. return 0;
  51. }

9.5.5 关系运算符重载

作用:重载关系运算符,可以让两个自定义类型的对象进行对比操作

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 重载关系运算符
  6. class Person {
  7. public:
  8. Person(string name, int age) {
  9. m_Name = name;
  10. m_Age = age;
  11. }
  12. // 重载关系==运算符
  13. bool operator==(Person& p) {
  14. if (this->m_Age == p.m_Age && this->m_Name == p.m_Name) {
  15. return true;
  16. }
  17. return false;
  18. }
  19. // 重载关系!=运算符
  20. bool operator!=(Person & p) {
  21. if (this->m_Age == p.m_Age && this->m_Name == p.m_Name) {
  22. return false;
  23. }
  24. return true;
  25. }
  26. string m_Name;
  27. int m_Age;
  28. };
  29. void test07() {
  30. Person p1("TOM", 12);
  31. Person p2("TMD", 12);
  32. if (p1 == p2) {
  33. cout << "p1和p2是相等的" << endl;
  34. }else {
  35. cout << "p1和p2不是相等的" << endl;
  36. }
  37. if (p1 != p2) {
  38. cout << "p1和p2bu是相等的" << endl;
  39. }
  40. else {
  41. cout << "p1和p2是相等的" << endl;
  42. }
  43. }
  44. int main() {
  45. test07();
  46. system("pause");
  47. return 0;
  48. }

9.5.6 函数调用运算符重载

函数调用运算符()也可以重载

由于重载后使用的方式非常像函数的调用,因此称为仿函数

仿函数没有固定写法,非常灵活

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. //函数调用运算符重载
  6. //打印输出类
  7. class MyPrint {
  8. public:
  9. //重载函数调用运算符
  10. void operator()(string test) {
  11. cout << test << endl;
  12. }
  13. };
  14. void test08() {
  15. MyPrint myPrint;
  16. myPrint("hello world");
  17.     // 匿名函数调用
  18.     MyPrint()("hello world");
  19. }
  20. int main() {
  21. test08();
  22. system("pause");
  23. return 0;
  24. }

9.6 继承

继承是面向对象三大特性之一

我们发现,定义这些类时,下级别的成员除了拥有上一级的特性,还有自己的特性

这个时候我们就可以考虑利用继承的技术,减少重复代码。

9.6.1 继承的基本用法

  1. //继承的好处:减少重复代码
  2. //语法: class 子类: 继承方式 父类
  3. //子类 也称派生类
  4. //父类 也成为基类
  5. // 派生类中的成员,包含两大部分:一类是从基类继承过来,一类是自己增加的成员,从基类继承过来的
  6. //表现其共性, 而新增的成员体现了其个性。
  7. #define _CRT_SECURE_NO_WARNINGS
  8. #include<iostream>
  9. #include<string>
  10. using namespace std;
  11. //公共页面
  12. class BasePage {
  13. public:
  14. void header() {
  15. cout << "首页、公开课、登录、注册...(公共头部)" << endl;
  16. }
  17. void footer() {
  18. cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;
  19. }
  20. void left() {
  21. cout << "Java、Python、C++...(公共分类列表)" << endl;
  22. }
  23. };
  24. //java页面
  25. class Java: public BasePage {
  26. public:
  27. void content() {
  28. cout << "Java 学科视频" << endl;
  29. }
  30. };
  31. class Python : public BasePage {
  32. public:
  33. void content() {
  34. cout << "Python学科视频" << endl;
  35. }
  36. };
  37. class C__ : public BasePage {
  38. public:
  39. void content() {
  40. cout << "C__ 学科视频" << endl;
  41. }
  42. };
  43. void test01() {
  44. cout << "Java页面如下" << endl;
  45. Java ja;
  46. ja.header();
  47. ja.footer();
  48. ja.left();
  49. ja.content();
  50. cout << "_____________" << endl;
  51. Python py;
  52. py.header();
  53. py.footer();
  54. py.left();
  55. py.content();
  56. cout << "_____________" << endl;
  57. C__ c;
  58. c.header();
  59. c.footer();
  60. c.left();
  61. c.content();
  62. }
  63. int main() {
  64. test01();
  65. system("pause");
  66. return 0;
  67. }

9.6.2 继承的方式

继承方式一共有三种:

  • 公共继承

  • 保护继承

  • 私有继承

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 继承方式
  6. class Base1 {
  7. public:
  8. int m_A;
  9. protected:
  10. int m_B;
  11. private:
  12. int m_C;
  13. };
  14. //公共继承
  15. class Son1 :public Base1 {
  16. public:
  17. void func() {
  18. m_A = 10;
  19. m_B = 10;
  20. //m_C = 10;//访问不到
  21. }
  22. };
  23. //保护继承
  24. class Son2 :protected Base1 {
  25. public:
  26. void func() {
  27. m_A = 10;
  28. m_B = 10;
  29. //m_C = 10;//访问不到
  30. }
  31. };
  32. //私有继承
  33. class Son3 :private Base1 {
  34. public:
  35. void func() {
  36. m_A = 10;
  37. m_B = 10;
  38. //m_C = 10;//访问不到
  39. }
  40. };
  41. void test02() {
  42. Son1 s1;
  43. //cout << "m_A = "<< s1.m_A << endl;
  44. s1.m_A = 100;
  45. cout << "m_A = " << s1.m_A << endl;
  46. //s1.m_B = 100; // 到Son1中 m_B是保护权限 类外访问不到
  47. //Son2 s2;
  48. //s2.m_A = 100;/ 到Son2中 m_A m_B是保护权限 类外访问不到
  49. //Son3 s3;
  50. //到Son2中 m_A m_B是私有权限 类外访问不到
  51. }
  52. int main() {
  53. test02();
  54. system("pause");
  55. return 0;
  56. }

9.6.3 继承中的对象模型

父类中所有非静态成员属性都会被子类继承下去, 只是由编译器给隐藏后访问不到

  1. //利用开发人员命令提示工具查看对象模型
  2. //跳转盘符 F:
  3. //跳转文件路径 cd 具体路径下
  4. //查看命名 cl /d1 reportSingleClassLayout类名 文件名

9.6.4 继承中构造和析构顺序

子类继承父类后,当创建子类对象,也会调用父类的构造函数

问题: 父类和子类的构造和析构顺序谁先谁后

继承中构造和析构顺序如下:

先构造父类,在构造子类,析构的顺序与构造的顺序相反。

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. class Base {
  6. public:
  7. Base() {
  8. cout << "Base构造函数!" << endl;
  9. }
  10. ~Base() {
  11. cout << "~Base的析构函数!" << endl;
  12. }
  13. };
  14. class Son :public Base {
  15. public:
  16. Son() {
  17. cout << "Son构造函数!" << endl;
  18. }
  19. ~Son() {
  20. cout << "~Son的析构函数!" << endl;
  21. }
  22. };
  23. void test04() {
  24. Son s;
  25. }
  26. int main() {
  27. test04();
  28. system("pause");
  29. return 0;
  30. }
  31. //Base构造函数!
  32. //Son构造函数!
  33. //~Son的析构函数!
  34. //~Base的析构函数!

9.6.5 继承同名成员处理方式

问题: 当子类与父类出现同名的成员,如何通过子类对象,访问到子类或父类中同名的数据呢?

  • 访问子类同名成员,直接访问即可

  • 访问父类同名成员,需要加作用域

  • 当子类与父类拥有同名的成员函数, 子类会隐藏父类中同名成员函数,加作用域可以访问到父类中同名函数。

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 继承中同名成员处理
  6. class Base {
  7. public:
  8. Base() {
  9. m_A = 100;
  10. }
  11. void func() {
  12. cout << "Base func()调用" << endl;
  13. }
  14. void func(int) {
  15. cout << "Base func(int)调用" << endl;
  16. }
  17. int m_A;
  18. };
  19. class Son :public Base {
  20. public:
  21. Son() {
  22. m_A = 10;
  23. cout << "m_A = " << this->m_A << endl;
  24. }
  25. void func() {
  26. cout << "son func()调用" << endl;
  27. }
  28. int m_A;
  29. };
  30. // 同名成员的属性的处理方式
  31. void test05() {
  32. Son s;
  33. cout << "m_A = " << s.m_A << endl;
  34. //如果 通过子类对象, 访问到父类中同名成员,需要加作用域
  35. cout << "Base m_A = " << s.Base::m_A << endl;
  36. }
  37. // 同名函数处理方式
  38. void test06() {
  39. Son s;
  40. s.func();
  41. s.Base::func();
  42. // 如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏掉父类中的所有同名成员函数(重载函数)
  43. // 如果想访问到父类中被隐藏的同名函数,需要加作用域
  44. s.Base::func(100);
  45. }
  46. int main() {
  47. test05();
  48. test06();
  49. system("pause");
  50. return 0;
  51. }

9.6.6 继承同名静态成员处理方式

问题: 继承中同名的静态成员在子类对象上如何进行访问?

静态成员和非静态成员出现同名,处理方式一致。

  • 访问子类同名成员,直接访问即可

  • 访问父类同名成员,需要加作用域

  • 有两种访问的方式(通过对象和通过类名)

9.6.7 多继承语法

C++允许一个类继承多个类

语法: class 子类:继承方式 父类1, 继承方式2 父类2....

多继承可能会引起父类中有同名成员出现, 需要加作用域区分

C++实际开发中不建议用多继承

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. //多继承的语法
  6. class Base1 {
  7. public:
  8. Base1() {
  9. m_A = 100;
  10. }
  11. int m_A;
  12. };
  13. //多继承的语法
  14. class Base2 {
  15. public:
  16. Base2() {
  17. m_A = 200;
  18. }
  19. int m_A;
  20. };
  21. class Son :public Base1, public Base2 {
  22. public:
  23. Son() {
  24. this->m_C = 300;
  25. this->m_D = 400;
  26. }
  27. int m_C;
  28. int m_D;
  29. };
  30. void test07() {
  31. Son s;
  32. cout << "sizeof = " << sizeof(s) << endl;
  33. // 当父类中出现同名成员,需要加作用域区分
  34. cout << "Base1 m_A = " << s.Base1::m_A << endl;
  35. cout << "Base2 m_A = " << s.Base2::m_A << endl;
  36. }
  37. int main() {
  38. test07();
  39. system("pause");
  40. return 0;
  41. }

9.6.8 菱形继承

菱形继承的概念:

两个派生类继承用一个基类

又有某个类同时继承着两个派生类

这种继承被称为菱形继承、或者钻石继承

总结:

  • 菱形继承带来的问题是子类继承两份相同的数据, 导致资源浪费以及毫无意义

  • 利用虚继承可以解决菱形继承问题 //继承之前 加上关键词 virtual 变为虚继承

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 动物类
  6. class Animal {
  7. public:
  8. int m_Age;
  9. };
  10. // 利用虚继承 解决菱形继承的问题
  11. // 继承之前 加上关键词 virtual 变为虚继承
  12. // Animal类称为虚基类
  13. //
  14. //羊类
  15. class Sheep :virtual public Animal {};
  16. //驼类
  17. class Alpaca :virtual public Animal {};
  18. //羊驼类
  19. class SheepAlpaca :public Sheep, public Alpaca {};
  20. void test09() {
  21. SheepAlpaca st;
  22. st.Sheep::m_Age = 100;
  23. st.Alpaca::m_Age = 10;
  24. // 当菱形继承,两个父类拥有相同数据,需要加以作用域区分
  25. cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl;
  26. cout << "st.Alpaca::m_Age = " << st.Alpaca::m_Age << endl;
  27. cout << "st.m_Age = " << st.m_Age << endl;
  28. }
  29. int main() {
  30. test09();
  31. system("pause");
  32. return 0;
  33. }

9.7 多态

9.7.1 多态的基本概念

多态是C++面向对象三大特性之一

多态分为两类

  • 静态多态: 函数重载和运算符重载属于静态多态,复用函数名

  • 动态多态: 派生类和虚函数实现运行时多态

静态多态和动态多态的区别:

  • 静态多态的函数地址早绑定-编译阶段确定函数地址

  • 动态多态的函数地址晚绑定-运行阶段确定函数地址

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. //多态
  6. //动物类
  7. class Animal {
  8. public:
  9. virtual void speak() {
  10. cout << "动物在说话" << endl;
  11. }
  12. };
  13. //猫类
  14. class Cat :public Animal {
  15. public:
  16. virtual void speak() {
  17. cout << "小猫 喵喵苗" << endl;
  18. }
  19. };
  20. //狗类
  21. class Dog :public Animal {
  22. public:
  23. virtual void speak() {
  24. cout << "小狗 汪汪汪" << endl;
  25. }
  26. };
  27. // 地址早绑定 在编译阶段确定函数地址
  28. //如果想执行让猫说话,那么这个函数地址就不能提前绑定,需要在运行阶段进行绑定,地址晚绑定
  29. //
  30. //动态多态满足的条件
  31. //1.有继承关系
  32. //2.子类重写父类的虚函数
  33. //重写 函数返回值类型 函数名 参数列表 完全相同
  34. // 动态多态的使用
  35. // 父类的指针或者引用 指向子类对象
  36. void doSpeak(Animal &animal) {
  37. animal.speak();
  38. }
  39. void tests01() {
  40. Cat cat;
  41. doSpeak(cat);
  42. Dog dog;
  43. doSpeak(dog);
  44. }
  45. int main() {
  46. tests01();
  47. system("pause");
  48. return 0;
  49. }

9.7.2 多态的原理剖析

空类的大小为1

9.7.3 多态案例 -计算机类

多态的优点:

  • 代码组织结构清晰

  • 可读性强

  • 利于前期和后期的扩展以及维护

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 分别利用普通写法和多态技术实现计算器
  6. // 普通写法
  7. class Calculator {
  8. public:
  9. int getResult(string oper) {
  10. if (oper == "+") {
  11. return m_Num1 + m_Num2;
  12. }
  13. else if (oper == "-") {
  14. return m_Num1 - m_Num2;
  15. }
  16. else if (oper == "*") {
  17. return m_Num1 * m_Num2;
  18. }
  19. //如果想扩展新的功能,需要修改源码
  20. //在真实开发中 提倡 开闭原则
  21. //开闭原则: 对扩展进行开放,对修改进行关闭
  22. return 0;
  23. }
  24. int m_Num1;// 操作数1
  25. int m_Num2;//操作数2
  26. };
  27. void test01() {
  28. //创建计算机对象
  29. Calculator c;
  30. c.m_Num1 = 10;
  31. c.m_Num2 = 10;
  32. cout << c.m_Num1 << " + " << c.m_Num2 << " = " << c.getResult("+") << endl;
  33. cout << c.m_Num1 << " - " << c.m_Num2 << " = " << c.getResult("-") << endl;
  34. cout << c.m_Num1 << " * " << c.m_Num2 << " = " << c.getResult("*") << endl;
  35. }
  36. //利用多态
  37. //实现计算机抽象类
  38. class AbstractCalculator {
  39. public:
  40. AbstractCalculator() {
  41. m_Num1 = 0;
  42. m_Num2 = 0;
  43. }
  44. virtual int getResult() {
  45. return 0;
  46. }
  47. int m_Num1;
  48. int m_Num2;
  49. };
  50. // 加法计算机器类
  51. class AddCalculator :public AbstractCalculator {
  52. public:
  53. int getResult() {
  54. return m_Num1 + m_Num2;
  55. }
  56. };
  57. // 减法计算机器类
  58. class SubCalculator :public AbstractCalculator {
  59. public:
  60. int getResult() {
  61. return m_Num1 - m_Num2;
  62. }
  63. };
  64. // 乘法计算机器类
  65. class MulCalculator :public AbstractCalculator {
  66. public:
  67. int getResult() {
  68. return m_Num1 * m_Num2;
  69. }
  70. };
  71. void test03() {
  72. //多态使用条件
  73. //父类指针或者引用指向子类对象
  74. //加法运算
  75. AbstractCalculator* abc = new AddCalculator;
  76. abc->m_Num1 = 10;
  77. abc->m_Num2 = 10;
  78. cout << abc->m_Num1 << " + " << abc->m_Num2 << " = " << abc->getResult() << endl;
  79. //用完记得销毁
  80. delete abc;
  81. //减法运算
  82. abc = new SubCalculator;
  83. abc->m_Num1 = 10;
  84. abc->m_Num2 = 10;
  85. cout << abc->m_Num1 << " - " << abc->m_Num2 << " = " << abc->getResult() << endl;
  86. //用完记得销毁
  87. delete abc;
  88. //乘法运算
  89. abc = new MulCalculator;
  90. abc->m_Num1 = 10;
  91. abc->m_Num2 = 10;
  92. cout << abc->m_Num1 << " * " << abc->m_Num2 << " = " << abc->getResult() << endl;
  93. //用完记得销毁
  94. delete abc;
  95. }
  96. int main() {
  97. //test01();
  98. test03();
  99. system("pause");
  100. return 0;
  101. }

9.7.4 纯虚函数和抽象类

在多态中, 通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容

因此可以将虚函数改为纯虚函数

纯虚函数语法: virtual 返回值类型 函数名 (参数列表) = 0

当类中有了纯虚函数,这个类也称为抽象类

抽象类的特点:

  • 无法实例化对象

  • 子类必须重写抽象类中的纯虚函数,否则也属于抽象类

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 纯虚函数和抽象类
  6. class Base {
  7. public:
  8. //纯虚函数
  9. virtual void func() = 0;
  10. };
  11. void test01() {
  12. //Base s; // 抽象类无法实例化对象
  13. }
  14. int main() {
  15. test01();
  16. system("pause");
  17. return 0;
  18. }

9.7.5 多态案例2 制作饮品

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. //多态的案例2制作饮品
  6. class AbstractDrinking {
  7. public:
  8. // 1.煮水
  9. virtual void Boil() = 0;
  10. //2. 冲泡
  11. virtual void Brew() = 0;
  12. //3. 倒入杯中
  13. virtual void PourInCup() = 0;
  14. //4.加入辅料
  15. virtual void PutSomething() = 0;
  16. //制作饮品
  17. void makeDrink() {
  18. this->Boil();
  19. this->Brew();
  20. this->PourInCup();
  21. this->PutSomething();
  22. }
  23. };
  24. //制作咖啡
  25. class Coffee :public AbstractDrinking {
  26. public:
  27. // 1.煮水
  28. virtual void Boil() {
  29. cout << "煮农夫山泉" << endl;
  30. }
  31. //2. 冲泡
  32. virtual void Brew() {
  33. cout << "冲泡咖啡" << endl;
  34. }
  35. //3. 倒入杯中
  36. virtual void PourInCup() {
  37. cout << "倒入杯中" << endl;
  38. }
  39. //4.加入辅料
  40. virtual void PutSomething() {
  41. cout << "加入糖和牛奶" << endl;
  42. }
  43. };
  44. //制作茶
  45. class Tea :public AbstractDrinking {
  46. public:
  47. // 1.煮水
  48. virtual void Boil() {
  49. cout << "煮矿泉水" << endl;
  50. }
  51. //2. 冲泡
  52. virtual void Brew() {
  53. cout << "冲泡茶叶" << endl;
  54. }
  55. //3. 倒入杯中
  56. virtual void PourInCup() {
  57. cout << "倒入杯中" << endl;
  58. }
  59. //4.加入辅料
  60. virtual void PutSomething() {
  61. cout << "加入柠檬" << endl;
  62. }
  63. };
  64. //制作函数
  65. void doWork(AbstractDrinking* abs) {
  66. abs->makeDrink();
  67. delete abs;
  68. }
  69. void test06() {
  70. // 制作咖啡
  71. doWork(new Coffee);
  72. cout << "___________" << endl;
  73. //制作茶叶
  74. doWork(new Tea);
  75. }
  76. int main() {
  77. test06();
  78. system("pause");
  79. return 0;
  80. }

9.7.6 虚析构和纯虚析构

多态使用时, 如果子类中有属性开辟到堆区, 那么父类指针在释放时无法调用到子类的析构代码

解决方式: 将父类中的析构函数改为虚析构或者纯虚析构

虚析构和纯虚析构共性:

  • 可以解决父类指针释放子类对象

  • 都需要有具体的函数实现

虚析构和纯析构区别:

  • 如果是纯虚析构,该类属于抽象类,无法实例化对象

虚析构语法:

virtual ~类名(){}

纯析构语法:

virtual ~类名()=0;

类名::类名(){}

总结:

  1. 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象出现的问题

  1. 如果子类中没有堆区数据,可以不写为虚析构或纯虚析构

  1. 拥有纯虚析构的类也属于抽象类

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. // 虚析构和纯虚析构
  6. class Animals {
  7. public:
  8. //纯虚函数
  9. Animals() {
  10. cout << "Animal构造函数调用" << endl;
  11. }
  12. // 利用虚析构可以解决 父类指针释放子类对象时不干净的问题
  13. //virtual ~Animals() {
  14. // cout << "Animal析构函数调用" << endl;
  15. //}
  16. //纯虚析构 类内声明 类外实现
  17. virtual ~Animals() = 0;
  18. virtual void speak() = 0;
  19. //virtual ~Animal() = 0;
  20. };
  21. //
  22. Animals::~Animals(){ cout << "Animal纯虚析构函数调用" << endl; }
  23. class Cats :public Animals {
  24. public:
  25. Cats(string name) {
  26. cout << "Cat构造函数的调用" << endl;
  27. this->m_Name = new string(name);
  28. }
  29. ~Cats() {
  30. if (this->m_Name != NULL) {
  31. cout << "Cat析构函数" << endl;
  32. delete this->m_Name;
  33. }
  34. }
  35. virtual void speak() {
  36. cout << *m_Name<< " 小猫在说话" << endl;
  37. }
  38. string* m_Name;
  39. };
  40. void test09() {
  41. Animals* animal = new Cats("汤姆");
  42. animal->speak();
  43. //父类指针在析构时候 不会调用子类中析构函数,导致子类如果有堆区属性,出现内存泄露
  44. delete animal;
  45. }
  46. int main() {
  47. test09();
  48. system("pause");
  49. return 0;
  50. }

9.7.7 多态案例3 电脑组装

案例描述:

电脑主要组成部件为CPU(用于计算), 显卡(用于显示),内存条(用于存储)

将每一个零件封装出抽象类,并且提供不同的厂商生产不同零件,例如lntel厂商和Lenovo厂商

创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口

测试时组装三台不同的电脑进行工作。

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. //抽象不同零件类
  6. //抽象CPU类
  7. class CPU {
  8. public:
  9. // 抽象计算函数
  10. virtual void calculate() = 0;
  11. };
  12. //抽象显卡类
  13. class VideoCard {
  14. public:
  15. // 抽象显示函数
  16. virtual void display() = 0;
  17. };
  18. //抽象内存条类
  19. class Memory {
  20. public:
  21. // 抽象存储函数
  22. virtual void storage() = 0;
  23. };
  24. //抽象电脑类
  25. class Computers {
  26. public:
  27. Computers(CPU* cpu, VideoCard* lenovoMemory, Memory* memory) {
  28. this->m_cpu = cpu;
  29. this->m_memory = memory;
  30. this->m_videocard = lenovoMemory;
  31. }
  32. ~Computers() {
  33. if (m_cpu != NULL) {
  34. delete m_cpu;
  35. m_cpu = NULL;
  36. }
  37. if (m_memory != NULL) {
  38. delete m_memory;
  39. m_memory = NULL;
  40. }
  41. if (m_videocard != NULL) {
  42. delete m_videocard;
  43. m_videocard = NULL;
  44. }
  45. }
  46. //提供工作的函数
  47. void work() {
  48. m_cpu->calculate();
  49. m_memory->storage();
  50. m_videocard->display();
  51. }
  52. private:
  53. CPU* m_cpu; // CPU的零件指针
  54. VideoCard* m_videocard; //显卡的零件指针
  55. Memory* m_memory; // 存储的零件指针
  56. };
  57. // 具体厂商
  58. // Intel厂商
  59. class IntelCPU :public CPU {
  60. virtual void calculate() {
  61. cout << "Intel的CPU开始计算了" << endl;
  62. }
  63. };
  64. class IntelVideoCard :public VideoCard {
  65. virtual void display() {
  66. cout << "Intel的显卡开始工作了" << endl;
  67. }
  68. };
  69. class IntelMemory :public Memory {
  70. virtual void storage() {
  71. cout << "Intel的内存条开始工作了" << endl;
  72. }
  73. };
  74. // Lenovo 厂商
  75. class LenovoCPU :public CPU {
  76. virtual void calculate() {
  77. cout << "Lenovo的CPU开始计算了" << endl;
  78. }
  79. };
  80. class LenovoVideoCard :public VideoCard {
  81. virtual void display() {
  82. cout << "Lenovo的显卡开始工作了" << endl;
  83. }
  84. };
  85. class LenovoMemory :public Memory {
  86. virtual void storage() {
  87. cout << "Lenovo的内存条开始工作了" << endl;
  88. }
  89. };
  90. void test10() {
  91. //第一台电脑零件
  92. CPU* intelCpu = new IntelCPU;
  93. VideoCard* intelvideocard = new IntelVideoCard;
  94. Memory* intelmemory = new IntelMemory;
  95. // 创建第一台电脑
  96. Computers* computers1 = new Computers(intelCpu, intelvideocard, intelmemory);
  97. computers1->work();
  98. delete computers1;
  99. cout << "------------------" << endl;
  100. //第二台电脑零件
  101. CPU* lenovoCPU = new LenovoCPU;
  102. VideoCard* lenovoVideoCard = new LenovoVideoCard;
  103. Memory* lenovoMemory = new LenovoMemory;
  104. // 创建第二台电脑
  105. Computers* computers2 = new Computers(lenovoCPU, lenovoVideoCard, lenovoMemory);
  106. computers2->work();
  107. delete computers2;
  108. cout << "------------------" << endl;
  109. // 创建第三台电脑
  110. Computers* computers3 = new Computers(new LenovoCPU, new IntelVideoCard, new LenovoMemory);
  111. computers3->work();
  112. delete computers3;
  113. }
  114. int main() {
  115. test10();
  116. system("pause");
  117. return 0;
  118. }

十 .文件操作

程序运行时产生的数据都属于临时数据,程序一旦运行结束都会释放。

通过文件可以将数据持久化

C++中对文件操作需要包含头文件<fstream>

文件类型分为两种:

  1. 文本文件: 文件以文本的ASCII码形式存储在计算机中。

  1. 二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂他们

操作文件的三大类:

  1. ofstream:写操作

  1. ifstream: 读操作

  1. fstream: 读写操作

10.1 写文件

写文件的步骤:

  1. 包含头文件 #include<fstream>

  1. 创建流对象 ofstream ofs;

  1. 打开文件 ofs.open("文件路径", 打开方式)

  1. 写数据ofs<<"写入的数据";

  1. 关闭文件 ofs.close();

文件打开方式:

ios::in 为读文件而打开文件

ios::out 为写文件而打开文件

ios::ate 初始位置:文件尾

ios::app 追加方式写文件

ios::trunc 如果文件存在先删除,在创建

ios::binary 二进制方式

注意: 文件打开可以配合使用, 利用|操作符

总结:

  • 文件操作必须包含头文件fstream

  • 读文件可以利用ofstream,或者fstream类

  • 打开文件时需要指定操作文件的路径,以及打开方式

  • 利用<< 可以向文件中写数据

  • 操作完毕,要关闭文件

  1. //写文件
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #include<iostream>
  4. #include<string>
  5. using namespace std;
  6. #include<fstream>
  7. //写文件
  8. void test01(){
  9. ofstream ofs;
  10. ofs.open("test.txt", ios::out);
  11. ofs << "姓名:张三" << endl;
  12. ofs << "年龄:12" << endl;
  13. ofs << "性别: 男" << endl;
  14. //文件关闭
  15. ofs.close();
  16. }
  17. int main() {
  18. test01();
  19. system("pause");
  20. return 0;
  21. }

10.2 读文件

读文件的步骤:

  1. 包含头文件 #include<fstream>

  1. 创建流对象 ifstream ifs;

  1. 打开文件 ifs.open("文件路径", 打开方式)

  1. 读数据: 四种方式读取

  1. 关闭文件 ifs.close();

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. #include<fstream>
  5. using namespace std;
  6. //读文件
  7. void test02() {
  8. ifstream ifs;
  9. ifs.open("test.txt", ios::in);
  10. if (!ifs.is_open()) {
  11. cout << "文件打开失败" << endl;
  12. return;
  13. }
  14. //读数据
  15. //
  16. //第一种
  17. char buf[1024] = { 0 };
  18. while (ifs >> buf) {
  19. cout << buf << endl;
  20. }
  21. //第二种
  22. //char buf[1024] = { 0 };
  23. //while (ifs.getline(buf, 1024)) {
  24. // cout << buf << endl;
  25. //}
  26. //第三种
  27. // string buf;
  28. //while (getline(ifs, buf)) {
  29. // cout << buf << endl;
  30. //}
  31. //第四种
  32. //char c;
  33. //while ((c = ifs.get()) != EOF) {
  34. // cout << c;
  35. //}
  36. //关闭文件
  37. ifs.close();
  38. }
  39. int main() {
  40. test02();
  41. system("pause");
  42. return 0;
  43. }

10.3 二进制文件

打开方式要指定为: ios::binary

10.3.1 写文件

二进制方式写文件主要利用对象调用成员函数write

函数原型: ostream& write(const char *buffer,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. #include<fstream>
  6. class Person {
  7. public:
  8. char m_Name[64];// 姓名
  9. int m_Age; //年龄
  10. };
  11. void test03() {
  12. ofstream ofs("person.txt", ios::out | ios::binary);
  13. Person p = { "张三",18 };
  14. ofs.write((const char*) & p, sizeof(Person));
  15. ofs.close();
  16. }
  17. int main() {
  18. test03();
  19. system("pause");
  20. return 0;
  21. }

10.3.2 读文件

二进制方式读文件主要利用对象调用成员函数read

函数原型: ostream& read(char *buffer,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. #include<fstream>
  6. class Person {
  7. public:
  8. char m_Name[64];// 姓名
  9. int m_Age; //年龄
  10. };
  11. void test04() {
  12. ifstream ifs;
  13. ifs.open("person.txt", ios::out | ios::binary);
  14. if (!ifs.is_open()) {
  15. cout << "文件打开失败" << endl;
  16. return;
  17. }
  18. Person p;
  19. ifs.read((char*) & p, sizeof(Person));
  20. cout << "姓名:" << p.m_Name << endl;
  21. cout << "年龄:" << p.m_Age << endl;
  22. ifs.close();
  23. }
  24. int main() {
  25. test04();
  26. system("pause");
  27. return 0;
  28. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/234422
推荐阅读
相关标签
  

闽ICP备14008679号