学习预览

学习共分为三个阶段:

  • 第一阶段:C++基础语法入门,对C++有初步了解,能够有几处编程能力
  • 第二阶段:C++核心编程,介绍C++面向对象编程,为大型项目做铺垫
  • 第三阶段:C++提高编程,介绍C++泛型编程思想,以及STL的基本使用

    C++基础

    程序流程结构

    选择结构

    if

    循环结构

    while
    do-while
    for

    跳转结构

    break:退出循环
    continue:结束本次循环,进入下次循环
    goto(不建议用)

    数组

    一维数组

    1、数组类型 数组名 [数组长度];
    2、数组类型 数组名 [数组长度]={值1,值2……}
    3、数组类型 数组名[]={值1,值2,……}
    一维数组名称用途:
    sizeof(arr):数组占用的内存空间
    (int)arr,(int)&arr[2]:数组首地址,每个元素的首地址
    冒泡排序法
    1、求最大值:

2、数组按大小逆置:

3、冒泡排序算法:

  1. #include<iostream>//头文件
  2. #include<string>
  3. using namespace std;
  4. int main()
  5. {
  6. //1、创建数组
  7. int arr[10] = { 7,8,6,3,2,5,0,1,4,9};
  8. cout << "冒泡前: " << endl;
  9. for (int i = 0; i < 10; i++)
  10. {
  11. cout << arr[i] << " ";
  12. }
  13. cout << endl;
  14. //2、排序
  15. for (int i = 0; i < 10; i++)
  16. {
  17. for (int j = 0; j < 10 - i - 1; j++)
  18. {
  19. if (arr[j] > arr[j+1])
  20. {
  21. //数字交换
  22. int temp = arr[j];
  23. arr[j] = arr[j + 1];
  24. arr[j + 1] = temp;
  25. }
  26. }
  27. }
  28. //3、打印
  29. cout << "冒泡后: " << endl;
  30. for (int i = 0; i < 10; i++)
  31. {
  32. cout << arr[i] << " ";
  33. }
  34. }

二维数组

二维数组定义
4种定义方法
二维数组名
1)可以查看占用内存大小;2)可以查看二维数组的首地址
image.png

函数

函数定义

1)返回值类型:一个函数名可以返回一个值,在函数中定义
2)函数名:给函数其名称;
3)参数列表:使用该函数时,传入的数据;
4)函数体语句:花括号内的代码,函数内需要执行的语句;
5)return表达式:和返回值类型挂钩,函数执行后,返回相应数据;
语法:
返回值类型 函数名 参数列表
{
函数体语句
return表达式
}

  1. int add(int a,int b)
  2. {
  3. int C = a + b;
  4. return C
  5. }

函数调用

语法: 函数名(参数列表)

值传递

实际参数和形式参数

函数常见样式

1)无参无返:void test()
2)有参无返:void test(参数列表)
3)无参有返:int test()
4)有参有返:int test(参数列表)

函数声明

提前通知函数的存在

函数的分文件编写

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

  1. #pragma once
  2. #include<iostream>
  3. using namespace std;
  4. void swap(int num1, int num2);
  5. int add(int num1, int num2);

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

  1. #include"head.h";
  2. int add(int num1, int num2)
  3. {
  4. int sum = num1 + num2;
  5. return sum;
  6. }
  1. #include"head.h";
  2. void swap(int num1, int num2)
  3. {
  4. int temp = num1;
  5. num1 = num2;
  6. num2 = temp;
  7. cout << "a的值为:" << num1 << endl;
  8. cout << "b的值为:" << num2<< endl;
  9. }

3、在头文件中写函数的声明
image.png
4、在源文件(main函数和被调函数)中写函数定义
image.png

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. #include"head.h";//自定义的头文件
  5. int main()
  6. {
  7. int a = 10;
  8. int b = 20;
  9. swap(a, b);
  10. int c = add(a, b);
  11. cout << "和为:" << c << endl;
  12. }

指针

指针定义

语法:数据类型 * 指针变量

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. int main()
  5. {
  6. int a = 10;
  7. int* p;
  8. p = &a;
  9. cout << "p的值为:" << p << endl;
  10. cout << "*p的值:" << *p << endl;
  11. }

指针占用空间大小

32位操作系统占用4字节;64位操作系统占用8字节

空指针

1)用以给指针变量进行初始化;2)空指针不可以进行访问。
int * p = NULL

野指针

指向非法空间
空指针和野指针不是我们能访问的空间

const修饰指针

const in p=&a(修饰指针指向的值)
int
const p=&b(修饰指针指向)
const int * const p = &a(修饰指针指向和指针指向的值)

指针和数组

利用指针访问数组中元素

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. #include"head.h";//自定义的头文件
  5. int main()
  6. {
  7. //指针和数组
  8. //利用指针访问数组中元素
  9. int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
  10. cout << "第一个元素位: " << arr[0] << endl;
  11. int* p = arr;
  12. cout << "指针指向元素为: " << *p << endl;
  13. p++;
  14. cout << "指针指向元素为: " << *p << endl;
  15. cout << "利用指针遍历数组 " << endl;
  16. int* p2 = arr;
  17. for (int i = 0; i < 10; i++)
  18. {
  19. cout << *p2 << endl;
  20. p2++;
  21. }
  22. }

指针和函数

使用地址传递:可以修改实参的值;
值传递:不可以修改实参的值。

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. #include"head.h";//自定义的头文件
  5. void swap02(int* p1, int* p2)
  6. {
  7. int temp = *p1;
  8. *p1 = *p2;
  9. *p2 = temp;
  10. }
  11. int main()
  12. {
  13. //指针和函数
  14. //
  15. int a = 10;
  16. int b = 20;
  17. swap02(&a, &b);
  18. cout << "a=" << a << endl;
  19. cout << "b=" << b << endl;
  20. }

指针、数组与函数的应用案例

案例描述:封装一个函数,利用冒泡排序,实现对整型数组的升序排序

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. #include"head.h";//自定义的头文件
  5. //冒泡排序函数
  6. void bubbsort(int* arr, int len)
  7. {
  8. for (int i = 0; i < len - 1; i++)
  9. {
  10. for (int j = 0; j < len - i - 1; j++)
  11. {
  12. if (arr[j] > arr[j + 1])
  13. {
  14. int temp = arr[j];
  15. arr[j] = arr[j + 1];
  16. arr[j + 1] = temp;
  17. }
  18. }
  19. }
  20. }
  21. void printArr(int* arr, int len)
  22. {
  23. for (int i = 0; i < len;i++)
  24. {
  25. cout << arr[i]<<" ";
  26. }
  27. cout << endl;
  28. }
  29. int main()
  30. {
  31. //1、先创建一个数组
  32. int arr[10] = {4,3,6,9,1,2,10,8,7,5};
  33. int len = sizeof(arr) / sizeof(arr[0]);
  34. cout << "原数组为: " << endl;
  35. printArr(arr, len);
  36. //2、创建函数,实现冒泡排序
  37. bubbsort(arr, len);
  38. //3、打印排序后的数组
  39. cout << "排序后为: " << endl;
  40. printArr(arr, len);
  41. system("pause");
  42. return 0;
  43. }

结构体

结构体的定义和使用

结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
创建方法:

  • struct 结构体名 变量名
  • struct 结构体名 变量名={成员数值1,成员数组2…..}
  • 在定义结构体时顺便创建结构体变量

image.png

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. #include"head.h";//自定义的头文件
  5. //1、创建学生数据类型 :学生包括(姓名。年龄,分数)
  6. //自定义数据类型,一些类型集合组成的一个类型
  7. //语法 struct 类型名
  8. //结构体定义
  9. struct Student
  10. {
  11. //成员列表
  12. //姓名
  13. string name;
  14. //年龄
  15. int age;
  16. //分数
  17. int score;
  18. }s3;
  19. int main()
  20. {
  21. //2、通过学生类型创建具体学生(三种方式)
  22. // 创建结构体变量时,Struct可以省略
  23. //2.1、struct Student s1
  24. Student s1;
  25. s1.name = "张三";
  26. s1.age = 18;
  27. s1.score = 100;
  28. cout << "姓名: " << s1.name << " 年龄: " << s1.age << " 分数: " << s1.score << endl;
  29. //2.2、struct Student s2={...}
  30. struct Student s2 = { "李四",19,80 };
  31. cout << "姓名: " << s2.name << " 年龄: " << s2.age << " 分数: " << s2.score << endl;
  32. //2.3、在定义结构体时顺便创建结构变量(不建议使用)
  33. s3.name = "王五";
  34. s3.age = 20;
  35. s3.score = 60;
  36. cout << "姓名: " << s3.name << " 年龄: " << s3.age << " 分数: " << s3.score << endl;
  37. }

结构体数组

作用:将自定义的结构体放入到数组中,方便维护
语法:struct 结构体名 数组名[元素数目]={…………..}

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. #include"head.h";//自定义的头文件
  5. //结构体数组
  6. //1、定义结构体
  7. struct Student
  8. {
  9. string name;
  10. int age;
  11. int score;
  12. };
  13. int main()
  14. {
  15. //2、创建结构体数组
  16. struct Student stuArray[3] =
  17. {
  18. {"张三",18,100},
  19. {"李四",28,99},
  20. {"王五",38,66}
  21. };
  22. //3、给结构体数组中的元素赋值、
  23. stuArray[2].name = "赵六";
  24. stuArray[2].age = 80;
  25. stuArray[2].score = 60;
  26. //4、遍历结构体数组
  27. for (int i = 0; i < 3; i++)
  28. {
  29. cout << " 姓名为:" << stuArray[i].name << " 年龄为: " << stuArray[i].age << " 分数为: " << stuArray[i].score << endl;
  30. }
  31. }

结构体指针

作用:利用结构体指针访问结构体中的成员

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //结构体指针
  5. //1、定义结构体
  6. struct Student
  7. {
  8. string name;
  9. int age;
  10. int score;
  11. };
  12. int main()
  13. {
  14. //1、创建学生结构体变量
  15. struct Student s = { "张三",18,100};
  16. //2、通过指针指向结构体变量
  17. struct Student * p = &s;
  18. //3、通过指针访问结构体变量中的数据
  19. cout << "姓名: " << p->name << " 年龄: " << p->age << " 分数: " << p->score << endl;
  20. }

结构体嵌套结构结构体

作用:结构体中的成员可以是另一个结构体

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //结构体嵌套结构体
  5. // 1、定义学生结构体
  6. struct student
  7. {
  8. string name;
  9. int age;
  10. int score;
  11. };
  12. //2、定义老师结构体
  13. struct teacher
  14. {
  15. int id;
  16. string name;
  17. int age;
  18. struct student stu;
  19. };
  20. int main()
  21. {
  22. //3、创建老师结构体变量
  23. struct teacher t;
  24. t.id = 10000;
  25. t.name = "老王";
  26. t.age = 50;
  27. t.stu.name = "小王";
  28. t.stu.age = 20;
  29. t.stu.score = 60;
  30. cout << "老师姓名:" << t.name << " 老师编号: " << t.id << " 老师年龄:" << t.age
  31. << " 学生姓名: " << t.stu.name << " 学生年龄: " << t.stu.age << " 学生成绩: " << t.stu.score << endl;
  32. }

结构体做函数参数

作用:接昂结构体作为参数向函数中传递
传递的两种方式:

  • 值传递(形参改变,实参不会改变)
  • 地址传递(形参改变,实参也会改变) ```cpp

    include //头文件

    include

    using namespace std;

//结构体嵌套结构体 // 1、定义学生结构体 struct Student { string name; int age; int score; };

//打印学生信息 //1、值传递 void printStudent(struct Student s) { cout << “姓名:” << s.name << “ 年龄: “ << s.age << “ 成绩: “ << s.score << endl; } //2、地址传递 //将形参改为指针,可以减少内存,而且不会复制新的副本 void printStudent(struct Student* p) { cout << “姓名:” << p->name << “ 年龄:” << p->age << “ 成绩:” << p->score << endl; } int main() { //结构体做函数参数 //创建结构体变量 struct Student s1; s1.name = “张三”; s1.age = 18; s1.score = 80;

  1. struct Student s2;
  2. s2.name = "李四";
  3. s2.age = 20;
  4. s2.score = 90;
  5. printStudent(s1);
  6. printStudent(&s2);

}

  1. <a name="mrTXp"></a>
  2. #### 结构体中Const的使用场景
  3. 作用:用const来防止误操作
  4. ```cpp
  5. #include<iostream> //头文件
  6. #include<string>
  7. using namespace std;
  8. //结构体嵌套结构体
  9. // 1、定义学生结构体
  10. struct Student
  11. {
  12. string name;
  13. int age;
  14. int score;
  15. };
  16. //打印学生信息
  17. //1、值传递
  18. void printStudent(struct Student s)
  19. {
  20. cout << "姓名:" << s.name << " 年龄: " << s.age << " 成绩: " << s.score << endl;
  21. }
  22. //2、地址传递
  23. void printStudent(const struct Student* p) //加入const后,一旦修改,就会报错
  24. {
  25. cout << "姓名:" << p->name << " 年龄:" << p->age << " 成绩:" << p->score << endl;
  26. }
  27. int main()
  28. {
  29. //结构体做函数参数
  30. //创建结构体变量
  31. struct Student s1;
  32. s1.name = "张三";
  33. s1.age = 18;
  34. s1.score = 80;
  35. struct Student s2;
  36. s2.name = "李四";
  37. s2.age = 20;
  38. s2.score = 90;
  39. printStudent(s1);
  40. printStudent(&s2);
  41. }

结构体实践

案例1:
image.png

  1. #include<iostream> //头文件
  2. #include<string>
  3. #include<ctime>
  4. using namespace std;
  5. //案列1
  6. // 定义学生结构体
  7. struct Student
  8. {
  9. string sname;
  10. int score;
  11. };
  12. // 定义老师结构体
  13. struct teacher
  14. {
  15. string tname;
  16. struct Student sArray[5];
  17. };
  18. //给老师和学生赋值的函数
  19. void allocatespace(struct teacher tArray[],int len)
  20. {
  21. string nameseed = "ABCDE";
  22. for (int i = 0;i < len;i++)
  23. {
  24. tArray[i].tname = "teacher_";
  25. tArray[i].tname += nameseed[i];
  26. //通过循环给每名老师带的学生赋值
  27. for (int j = 0; j < 5; j++)
  28. {
  29. tArray[i].sArray[j].sname = "Student";
  30. tArray[i].sArray[j].sname += nameseed[j];//字符串拼接
  31. int random = rand() % 61 + 40; //使用随机数定义[40,100]的分数区间
  32. tArray[i].sArray[j].score = random;
  33. }
  34. }
  35. }
  36. void printInfo(struct teacher tArray[],int len)
  37. {
  38. for (int i = 0; i < len; i++)
  39. {
  40. cout << "老师姓名:" << tArray[i].tname << endl;
  41. for (int j = 0;j < 5;j++)
  42. {
  43. cout << "\t学生姓名:" << tArray[i].sArray[j].sname <<" "<<
  44. "考试分数:" << tArray[i].sArray[j].score << endl;
  45. }
  46. }
  47. }
  48. int main()
  49. {
  50. //随机种子(作用是使分数更加随机?)
  51. srand((unsigned int)time(NULL));
  52. //1、创建3名老师的数组
  53. struct teacher tArray[3];
  54. //2、通过函数给3名老师的信息赋值,并给老师带的学生信息赋值;
  55. int len = sizeof(tArray) / sizeof(tArray[0]);
  56. allocatespace(tArray, len);
  57. //3、打印所有老师及所带学生信息
  58. printInfo(tArray, len);
  59. }

案例2:
image.png

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //案列2
  5. //1、创建英雄数组
  6. struct Hero
  7. {
  8. string name;
  9. int age;
  10. string sex;
  11. };
  12. //冒泡排序
  13. void bubbleSort(struct Hero heroArray[],int len)
  14. {
  15. for (int i = 0;i < len - 1;i++)
  16. for (int j = 0; j < len - i - 1; j++)
  17. {
  18. if (heroArray[j].age > heroArray[j + 1].age)
  19. {
  20. struct Hero temp = heroArray[j];
  21. heroArray[j] = heroArray[j + 1];
  22. heroArray[j + 1] = temp;
  23. }
  24. }
  25. }
  26. //打印程序
  27. void printHero(struct Hero heroArray[], int len)
  28. {
  29. for (int i = 0; i < len; i++)
  30. {
  31. cout << "姓名: " << heroArray[i].name << " 年龄:" << heroArray[i].age
  32. << " 性别:" << heroArray[i].sex<< endl;
  33. }
  34. }
  35. int main()
  36. {
  37. //2、创建数组存放5名英雄
  38. struct Hero heroArray[5] =
  39. {
  40. {"刘备",23,"男"},
  41. {"关羽",22,"男"},
  42. {"张飞",20,"男"},
  43. {"赵云",21,"男"},
  44. {"貂蝉",19,"女"}
  45. };
  46. int len = sizeof(heroArray) / sizeof(heroArray[0]);
  47. //3、对数组排序,按照年龄顺序
  48. bubbleSort(heroArray, len);
  49. //4、打印输出
  50. printHero(heroArray, len);
  51. }

项目开发实战

通讯录管理系统

1、退出系统
2、添加联系人
image.png

  1. void addPerson(Addressbooks * abs)
  2. {
  3. //判断通讯是否已满,如满就不添加
  4. if (abs->m_Size > MAX)
  5. {
  6. cout << "通讯录已满,无法添加!" << endl;
  7. return;
  8. }
  9. else
  10. {
  11. //添加具体联系人
  12. //姓名
  13. string name;
  14. cout << "请输入姓名:" << endl;
  15. cin >> name;
  16. abs->personArray[abs->m_Size].m_Name = name;
  17. //性别
  18. cout << "请输入性别:" << endl;
  19. cout << "1---男" << endl;
  20. cout << "2---女" << endl;
  21. int sex = 0;
  22. while (true)
  23. {
  24. cin >> sex;
  25. if (sex == 1 || sex == 2)
  26. {
  27. //如果输入1或2,可以退出循环,如果不是,重新输入
  28. abs->personArray[abs->m_Size].m_Sex = sex;
  29. break;
  30. }
  31. cout << "输入有误,清重新输入!" << endl;
  32. }
  33. //年龄
  34. cout << "请输入年龄:" << endl;
  35. int age = 0;
  36. cin >> age;
  37. abs->personArray[abs->m_Size].m_Age = age;
  38. //电话
  39. cout << "请输入联系电话:" << endl;
  40. string phone;
  41. cin >> phone;
  42. abs->personArray[abs->m_Size].m_Phone = phone;
  43. //住址
  44. cout << "请输入家庭住址:" << endl;
  45. string address;
  46. cin >> address;
  47. abs->personArray[abs->m_Size].m_Addr = address;
  48. //更新通讯录人数
  49. abs->m_Size++;
  50. cout << "添加成功!" << endl;
  51. system("pause"); //请按任意键继续
  52. system("cls"); //清屏操作
  53. }
  54. }

3、显示联系人
image.png
封装显示联系人的思路:
PS:1)三目运算符的使用;2)转置运算符”\t”

  1. void showPerson(Addressbooks* abs)
  2. {
  3. //判断通讯录中人数是否为0,提示记录为空
  4. //如果不是0,显示记录的联系人信息
  5. if (abs->m_Size == 0)
  6. {
  7. cout << "当前记录为空" << endl;
  8. }
  9. else
  10. {
  11. for (int i = 0; i < abs->m_Size; i++)
  12. {
  13. cout << "姓名: " <<abs->personArray[i].m_Name<<"\t";
  14. cout << "性别: " <<(abs->personArray[i].m_Sex == 1?"男":"女") << "\t"; //使用三目运算符简化代码
  15. cout << "年龄: " << abs->personArray[i].m_Age << "\t";
  16. cout << "电话: " << abs->personArray[i].m_Phone << "\t";
  17. cout << "住址: " << abs->personArray[i].m_Addr << endl;
  18. }
  19. }
  20. system("pause");
  21. system("cls");
  22. }

4、删除联系人
image.png

  1. //检测联系人是否存在(如果存在,返回联系人具体位置,不存在返回-1)
  2. //参数1 通讯录, 参数2 对比姓名
  3. int isExist(Addressbooks* abs, string name)
  4. {
  5. for (int i = 0; i < abs->m_Size; i++)
  6. {
  7. //
  8. if (abs->personArray[i].m_Name == name)
  9. {
  10. return i;
  11. }
  12. else
  13. {
  14. return -1;
  15. }
  16. }
  17. }
  1. //删除联系人
  2. void deletePerson(Addressbooks* abs)
  3. {
  4. cout << "请输入要删除人员姓名:" << endl;
  5. string name;
  6. cin >> name;
  7. //ret =-1 未查到
  8. //ret !=-1 查到
  9. int ret = isExist(abs, name);
  10. if (ret != -1)
  11. {
  12. //查到此人,要进行删除操作
  13. for (int i = ret; i < abs->m_Size; i++)
  14. {
  15. //数据前移
  16. abs->personArray[i] = abs->personArray[i + 1];
  17. }
  18. abs->m_Size--;//更新通讯录中的人员数
  19. cout << "删除成功" << endl;
  20. }
  21. else
  22. {
  23. cout << "查无此人" << endl;
  24. }
  25. system("pause");
  26. system("cls");
  27. }

5、查找联系人
image.png

  1. //查找联系人
  2. void findPerson(Addressbooks* abs)
  3. {
  4. cout << "请输入要查找的联系人:" << endl;
  5. string name;
  6. cin >> name;
  7. //判断指定联系人是否在通讯录中
  8. int ret = isExist(abs, name);
  9. if (ret != -1) //找到联系人
  10. {
  11. cout << "姓名:" << abs->personArray[ret].m_Name << endl;
  12. cout << "性别:" << abs->personArray[ret].m_Sex << endl;
  13. cout << "年龄:" << abs->personArray[ret].m_Age << endl;
  14. cout << "电话:" << abs->personArray[ret].m_Phone << endl;
  15. cout << "住址:" << abs->personArray[ret].m_Sex << endl;
  16. }
  17. else //未找到联系人
  18. {
  19. cout << "查无此人" << endl;
  20. }
  21. //按任意键清屏
  22. system("pause");
  23. system("cls");
  24. }

5、修改联系人
image.png

  1. //修改联系人
  2. void modifyPerson(Addressbooks* abs)
  3. {
  4. cout << "请输入要修改人的姓名:" << endl;
  5. string name;
  6. cin >> name;
  7. int ret = isExist(abs, name);
  8. if (ret != -1)
  9. {
  10. //姓名
  11. string name;
  12. cout << "请输入姓名:" << endl;
  13. cin >> name;
  14. abs->personArray[ret].m_Name = name;
  15. //性别
  16. cout << "请输入性别:" << endl;
  17. cout << "1---男" << endl;
  18. cout << "2---女" << endl;
  19. int sex = 0;
  20. while (true)
  21. {
  22. cin >> sex;
  23. if (sex == 1 || sex == 2)
  24. {
  25. //输入正确,退出循环输入
  26. abs->personArray[ret].m_Sex = sex;
  27. break;
  28. }
  29. else
  30. {
  31. cout << "输入有误,请重新输入!" << endl;
  32. }
  33. }
  34. //年龄
  35. int age;
  36. cout << "请输入年龄:" << endl;
  37. cin >> age;
  38. abs->personArray[ret].m_Age = age;
  39. //联系电话
  40. string phone;
  41. cout << "请输入联系方式:" << endl;
  42. cin >> phone;
  43. abs->personArray[ret].m_Phone = phone;
  44. //住址
  45. cout << "请输入家庭住址:" << endl;
  46. string address;
  47. cin >> address;
  48. abs->personArray[ret].m_Addr = address;
  49. cout << "已修改成功!" << endl;
  50. }
  51. else
  52. {
  53. cout << "查无此人" << endl;
  54. }
  55. system("pause"); //按任意键继续
  56. system("cls"); //修改完成后清屏
  57. }

6、清空联系人
image.png

  1. //清空联系人
  2. void cleanPerson(Addressbooks* abs)
  3. {
  4. abs->m_Size = 0; //将当期记录联系人数量置0,做逻辑清空操作
  5. cout << "通讯录已清空!" << endl;
  6. system("pause");
  7. system("cls");
  8. }

全部程序

  1. //-封装函数显示该界面 如void showMenu()
  2. //-在main函数中调用封装好的函数
  3. #include <iostream>
  4. #include <string>
  5. #define MAX 1000 //宏定义数目
  6. using namespace std;
  7. //菜单界面
  8. void showMenu()
  9. {
  10. cout << "**********************" << endl;
  11. cout << "*****1、添加联系人*****" << endl;
  12. cout << "*****2、显示联系人*****" << endl;
  13. cout << "*****3、删除联系人*****" << endl;
  14. cout << "*****4、查找联系人*****" << endl;
  15. cout << "*****5、修改联系人*****" << endl;
  16. cout << "*****6、清空联系人*****" << endl;
  17. cout << "*****0、退出通讯录*****" << endl;
  18. cout << "**********************" << endl;
  19. }
  20. //设计联系人结构体
  21. struct person
  22. {
  23. string m_Name; //姓名
  24. int m_Sex; //性别:1、男 2、女
  25. int m_Age; //年龄
  26. string m_Phone; //电话
  27. string m_Addr; //住址
  28. };
  29. //设计通讯录结构体
  30. struct Addressbooks
  31. {
  32. struct person personArray[MAX]; //通讯录中保存的联系人数组
  33. int m_Size; //通讯录中当前记录联系人个数
  34. };
  35. //1、添加联系人
  36. void addPerson(Addressbooks * abs)
  37. {
  38. //判断通讯是否已满,如满就不添加
  39. if (abs->m_Size > MAX)
  40. {
  41. cout << "通讯录已满,无法添加!" << endl;
  42. return;
  43. }
  44. else
  45. {
  46. //添加具体联系人
  47. //姓名
  48. string name;
  49. cout << "请输入姓名:" << endl;
  50. cin >> name;
  51. abs->personArray[abs->m_Size].m_Name = name;
  52. //性别
  53. cout << "请输入性别:" << endl;
  54. cout << "1---男" << endl;
  55. cout << "2---女" << endl;
  56. int sex = 0;
  57. while (true)
  58. {
  59. cin >> sex;
  60. if (sex == 1 || sex == 2)
  61. {
  62. //如果输入1或2,可以退出循环,如果不是,重新输入
  63. abs->personArray[abs->m_Size].m_Sex = sex;
  64. break;
  65. }
  66. cout << "输入有误,清重新输入!" << endl;
  67. }
  68. //年龄
  69. cout << "请输入年龄:" << endl;
  70. int age = 0;
  71. cin >> age;
  72. abs->personArray[abs->m_Size].m_Age = age;
  73. //电话
  74. cout << "请输入联系电话:" << endl;
  75. string phone;
  76. cin >> phone;
  77. abs->personArray[abs->m_Size].m_Phone = phone;
  78. //住址
  79. cout << "请输入家庭住址:" << endl;
  80. string address;
  81. cin >> address;
  82. abs->personArray[abs->m_Size].m_Addr = address;
  83. //更新通讯录人数
  84. abs->m_Size++;
  85. cout << "添加成功!" << endl;
  86. system("pause"); //请按任意键继续
  87. system("cls"); //清屏操作
  88. }
  89. }
  90. //2、显示联系人
  91. void showPerson(Addressbooks* abs)
  92. {
  93. //判断通讯录中人数是否为0,提示记录为空
  94. //如果不是0,显示记录的联系人信息
  95. if (abs->m_Size == 0)
  96. {
  97. cout << "当前记录为空" << endl;
  98. }
  99. else
  100. {
  101. for (int i = 0; i < abs->m_Size; i++)
  102. {
  103. cout << "姓名: " <<abs->personArray[i].m_Name<<"\t";
  104. cout << "性别: " <<(abs->personArray[i].m_Sex == 1?"男":"女") << "\t"; //使用三目运算符简化代码
  105. cout << "年龄: " << abs->personArray[i].m_Age << "\t";
  106. cout << "电话: " << abs->personArray[i].m_Phone << "\t";
  107. cout << "住址: " << abs->personArray[i].m_Addr << endl;
  108. }
  109. }
  110. system("pause");
  111. system("cls");
  112. }
  113. //检测联系人是否存在(如果存在,返回联系人具体位置,不存在返回-1)
  114. //参数1 通讯录, 参数2 对比姓名
  115. int isExist(Addressbooks* abs, string name)
  116. {
  117. for (int i = 0; i < abs->m_Size; i++)
  118. {
  119. //
  120. if (abs->personArray[i].m_Name == name)
  121. {
  122. return i;
  123. }
  124. else
  125. {
  126. return -1;
  127. }
  128. }
  129. }
  130. //删除联系人
  131. void deletePerson(Addressbooks* abs)
  132. {
  133. cout << "请输入要删除人员姓名:" << endl;
  134. string name;
  135. cin >> name;
  136. //ret =-1 未查到
  137. //ret !=-1 查到
  138. int ret = isExist(abs, name);
  139. if (ret != -1)
  140. {
  141. //查到此人,要进行删除操作
  142. for (int i = ret; i < abs->m_Size; i++)
  143. {
  144. //数据前移
  145. abs->personArray[i] = abs->personArray[i + 1];
  146. }
  147. abs->m_Size--;//更新通讯录中的人员数
  148. cout << "删除成功" << endl;
  149. }
  150. else
  151. {
  152. cout << "查无此人" << endl;
  153. }
  154. system("pause");
  155. system("cls");
  156. }
  157. //查找联系人
  158. void findPerson(Addressbooks* abs)
  159. {
  160. cout << "请输入要查找的联系人:" << endl;
  161. string name;
  162. cin >> name;
  163. //判断指定联系人是否在通讯录中
  164. int ret = isExist(abs, name);
  165. if (ret != -1) //找到联系人
  166. {
  167. cout << "姓名:" << abs->personArray[ret].m_Name << endl;
  168. cout << "性别:" << abs->personArray[ret].m_Sex << endl;
  169. cout << "年龄:" << abs->personArray[ret].m_Age << endl;
  170. cout << "电话:" << abs->personArray[ret].m_Phone << endl;
  171. cout << "住址:" << abs->personArray[ret].m_Sex << endl;
  172. }
  173. else //未找到联系人
  174. {
  175. cout << "查无此人" << endl;
  176. }
  177. //按任意键清屏
  178. system("pause");
  179. system("cls");
  180. }
  181. //修改联系人
  182. void modifyPerson(Addressbooks* abs)
  183. {
  184. cout << "请输入要修改人的姓名:" << endl;
  185. string name;
  186. cin >> name;
  187. int ret = isExist(abs, name);
  188. if (ret != -1)
  189. {
  190. //姓名
  191. string name;
  192. cout << "请输入姓名:" << endl;
  193. cin >> name;
  194. abs->personArray[ret].m_Name = name;
  195. //性别
  196. cout << "请输入性别:" << endl;
  197. cout << "1---男" << endl;
  198. cout << "2---女" << endl;
  199. int sex = 0;
  200. while (true)
  201. {
  202. cin >> sex;
  203. if (sex == 1 || sex == 2)
  204. {
  205. //输入正确,退出循环输入
  206. abs->personArray[ret].m_Sex = sex;
  207. break;
  208. }
  209. else
  210. {
  211. cout << "输入有误,请重新输入!" << endl;
  212. }
  213. }
  214. //年龄
  215. int age;
  216. cout << "请输入年龄:" << endl;
  217. cin >> age;
  218. abs->personArray[ret].m_Age = age;
  219. //联系电话
  220. string phone;
  221. cout << "请输入联系方式:" << endl;
  222. cin >> phone;
  223. abs->personArray[ret].m_Phone = phone;
  224. //住址
  225. cout << "请输入家庭住址:" << endl;
  226. string address;
  227. cin >> address;
  228. abs->personArray[ret].m_Addr = address;
  229. cout << "已修改成功!" << endl;
  230. }
  231. else
  232. {
  233. cout << "查无此人" << endl;
  234. }
  235. system("pause"); //按任意键继续
  236. system("cls"); //修改完成后清屏
  237. }
  238. //清空联系人
  239. void cleanPerson(Addressbooks* abs)
  240. {
  241. abs->m_Size = 0; //将当期记录联系人数量置0,做逻辑清空操作
  242. cout << "通讯录已清空!" << endl;
  243. system("pause");
  244. system("cls");
  245. }
  246. int main()
  247. {
  248. //创建通讯录结构体变量
  249. Addressbooks abs;
  250. //初始化
  251. abs.m_Size = 0;
  252. int select = 0;//创建用户选择输入的变量
  253. while (true)
  254. {
  255. //菜单调用
  256. showMenu();
  257. cin >> select;
  258. switch (select)
  259. {
  260. case 1: //添加联系人
  261. addPerson(&abs);
  262. break;
  263. case 2: //显示联系人
  264. showPerson(&abs);
  265. break;
  266. case 3: //删除联系人
  267. deletePerson(&abs);
  268. break;
  269. case 4: //查找联系人
  270. findPerson(&abs);
  271. break;
  272. case 5: //修改联系人
  273. modifyPerson(&abs);
  274. break;
  275. case 6: //清空联系人
  276. cleanPerson(&abs);
  277. break;
  278. case 0: //退出通讯录
  279. cout << "欢迎下次使用" << endl;
  280. system("pause"); //按任意键继续
  281. return 0;
  282. break;
  283. default:
  284. break;
  285. }
  286. }
  287. system("pause"); //请按任意键继续
  288. return 0;
  289. }

C++核心编程

本阶段主要针对C++面向对象编程技术做详细讲解,探讨C++的核心和精髓

内存分区模型

四个区的划分:
image.png

  1. #include<iostream> //头文件
  2. #include<string>
  3. #include<ctime>
  4. using namespace std;
  5. //全局变量、静态变量、常量
  6. //全局变量
  7. int g_a = 10;
  8. int g_b = 10;
  9. //const修饰的全局变量
  10. const int c_g_a = 10;
  11. const int c_g_b = 10;
  12. int main()
  13. {
  14. cout << "全局变量g_a的地址为:" << &g_a << endl;
  15. cout << "全局变量g_b的地址为:" << &g_b << endl;
  16. cout << "全局常量c_g_a的地址为:" << &c_g_a << endl;
  17. cout << "全局常量c_g_b的地址为:" << &c_g_b << endl;
  18. //静态变量 在普通变量前添加static
  19. static int s_a = 10;
  20. static int s_b = 10;
  21. cout << "静态变量s_a的地址为:" << (int)&s_a << endl;
  22. cout << "静态变量s_b的地址为:" << (int)&s_b << endl;
  23. //创建普通局部变量
  24. int l_a = 10;
  25. int l_b = 10;
  26. cout << "局部变量l_a的地址为:" << &l_a << endl;
  27. cout << "局部变量l_b的地址为:" << &l_b << endl;
  28. //创建局部常量
  29. const int c_l_a = 10;
  30. const int c_l_b = 10;
  31. cout << "局部常量c_l_a的地址为:" << &c_l_a << endl;
  32. cout << "局部常量c_l_b的地址为:" << &c_l_b << endl;
  33. //常量
  34. //字符串常量
  35. cout << "字符串常量的地址为:" << (int)&"hello world" << endl;
  36. //const修饰的全局变量,const修饰的局部变量
  37. system("pause");
  38. return 0;
  39. }

程序运行前

在程序编译后,生成了exe可执行程序,未执行该程序前分为两个阶段
代码区:1)只读;2)共享
全局区:该区域的数据在程序结构后由操作系统释放
image.png

程序运行中

image.png
局部变量存放在栈区,函数运行完成,自动清理

  1. int * func()
  2. {
  3. int a = 10;
  4. return &a; //返回局部变量地址,有误
  5. }
  6. int main()
  7. {
  8. int * p = func();
  9. cout<<*p<<endl; //编译器保留一次局部变量数据
  10. cout<<*p<<endl; //编译器不会保存两次局部变量数据
  11. system("pause");
  12. return 0;
  13. }

image.png

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

image.png

new操作符

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //1、new的基本语法
  5. int* func()
  6. {
  7. //在堆区创建整型数据
  8. //new返回使该整型类型的指针
  9. int* p = new int(10);
  10. return p;
  11. }
  12. //2、在堆区利用new开辟数组
  13. void test02()
  14. {
  15. //创建
  16. int* arr = new int[10]; //10代表数组由10各元素
  17. for (int i = 0; i < 10; i++)
  18. {
  19. arr[i] = i + 100;
  20. }
  21. for (int i = 0; i < 10; i++)
  22. {
  23. cout << arr[i] << endl;
  24. }
  25. //释放堆区数组
  26. //释放数组的时候,要加[]才行
  27. }
  28. int main()
  29. {
  30. int* p = func();
  31. cout << *p << endl;
  32. cout << *p << endl;
  33. test02();
  34. system("pause");
  35. return 0;
  36. }

引用

引用的基本使用

image.png

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. int main()
  5. {
  6. int a = 10;
  7. int& b = a; //变量a的别名为b
  8. cout << "a=" << a << endl;
  9. cout << "b=" << b << endl;
  10. system("pause");
  11. return 0;
  12. }

引用注意事项

  • 引用必须初始化(int &b;,错误);
  • 引用之后就不可以改变(如果定义为a的别名,就不能设置为其他变量的别名)

    引用做函数参数

    作用:函数传参时,可以利用引用的技术让形参修饰实参
    优点:可以简化指针修改实参 ```cpp

    include //头文件

    include

    using namespace std;

//交换函数

//1、值传递 void myswap01(int a, int b) { int temp = a; a = b; b = temp; } //2、地址传递 void myswap02(int a, int b) { int temp = a; a = b; b = temp; }

//3、引用传递 void myswap03(int &a, int &b) { int temp = a; a = b; b = temp; }

int main() { int a = 10; int b = 20;
//myswap01(a,b); //值传递,形参无法修改实参 myswap02(&a, &b); //指针传递,形参可以修改实参 //myswap03(a,b); // 引用传递,形参可以修改实参

  1. cout << "a=" << a << endl;
  2. cout << "b=" << b << endl;
  3. system("pause");
  4. return 0;

}

  1. <a name="cGDci"></a>
  2. #### 引用做函数返回值
  3. ```cpp
  4. #include<iostream> //头文件
  5. #include<string>
  6. using namespace std;
  7. //函数做函数返回值
  8. //1、不要返回局部变量的引用
  9. //2、函数的调用可以作为左值
  10. //返回局部变量引用
  11. int& test01()
  12. {
  13. int a = 10;
  14. return a;
  15. }
  16. //返回静态变量引用
  17. int& test02()
  18. {
  19. static int b = 10;
  20. return b;
  21. }
  22. int main()
  23. {
  24. //不要返回局部变量的引用
  25. int& ref = test01();
  26. cout << "ref=" << ref << endl;
  27. cout << "ref=" << ref << endl;
  28. //如果函数做左值,那么必须返回引用
  29. int& ref2 = test02();
  30. cout << "ref2=" << ref2 << endl;
  31. cout << "ref2=" << ref2 << endl;
  32. test02() = 1000;
  33. cout << "ref2=" << ref2 << endl;
  34. cout << "ref2=" << ref2 << endl;
  35. system("pause");
  36. return 0;
  37. }

引用的本质

本质:引用本质在C++中内部实现是一个指针常量
结论:C++推荐用引用技术,因为语法方便,引用本质为指针常量,但是所有指针操作编译器都帮我们做了

常量引用

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //打印函数
  5. void showvalue(const int& val) //添加const,形参无法改变
  6. {
  7. //val = 1000; 形参无法改变
  8. cout << "val=" << val << endl;
  9. }
  10. int main()
  11. {
  12. //常量引用
  13. //使用场景:用来修饰形参,防止误操作
  14. int a = 100;
  15. showvalue(a);
  16. system("pause");
  17. return 0;
  18. }

函数提高

函数默认参数

在C++中,函数的形参列表中的形参是可以有默认值的。
语法:返回值类型 函数名 (参数 = 默认值){ }

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //函数默认参数
  5. //如果我们自己传入数据,有用自己的数据,没有就用默认值
  6. //语法:返回值类型 函数名(形参=默认值){}
  7. int func(int a,int b = 20,int c = 30) //b和c用的默认值
  8. {
  9. return a + b + c;
  10. }
  11. int func2(int a = 10, int b = 10); //2、如果函数声明有默认参数,函数实现就不能有默认参数
  12. int main()
  13. {
  14. //注意事项
  15. //1、如果某个位置有了默认参数,那么从这个位置往后的形参都要有默认值
  16. cout << func(10) << endl; //b和c使用形参列表中的默认值
  17. cout << func(10, 30) << endl; //b使用实参列表中的值
  18. cout << func2(10, 10) << endl;
  19. }
  20. int func2(int a,int b)//函数实现就不能有默认参数
  21. {
  22. return a + b;
  23. }

函数占位参数

C++中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该变量
语法:返回值类型 函数名(数据类型){}

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //占位参数
  5. //语法:返回值类型 函数名(数据类型){}
  6. //占位参数还可以是默认参数
  7. void func(int a, int = 10)
  8. {
  9. cout << "this is func" << endl;
  10. }
  11. int main()
  12. {
  13. func(10, 10);
  14. system("pause");
  15. return 0;
  16. }

函数重载-基本语法

作用:函数名可以相同,提高函数名的复用性
函数重载满足条件:

  • 同一作用域下
  • 函数名相同
  • 函数参数类型不同或个数不同或顺序不同

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

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //函数重载
  5. //可以让函数名重复使用,提高复用性
  6. // 满足条件:
  7. //1、同一作用域下
  8. //2、函数名称相同
  9. //3、函数参数类型不同,个数不同,顺序不同
  10. void func()
  11. {
  12. cout << "" << endl;
  13. }
  14. void func(int a)
  15. {
  16. cout << "this is func" << endl;
  17. }
  18. void func(int a, double b) //形参数目不同
  19. {
  20. cout << "3" << endl;
  21. }
  22. void func(double a, int b) //形参顺序不同
  23. {
  24. cout << "4" << endl;
  25. }
  26. int main()
  27. {
  28. func(); // 调用第一个func函数
  29. func(10);//调用第二个func函数
  30. system("pause");
  31. return 0;
  32. }

函数重载-注意事项

  • 引用作为重载条件
  • 函数重载碰到默认参数(尽量避免出现) ```cpp

    include //头文件

    include

    using namespace std;

//函数重载的注意事项 //1、引用作为重载条件 void func(int& a) { cout << “func(int &a)调用” << endl; }

void func(const int& a) { cout << “func(const int &a)调用” << endl; }

//2、函数重载碰到默认参数 void func2(int a, int b = 10) { cout << “调用func2(int a, int b = 10)” << endl; }

void func2(int a) { cout << “调用func2(int a)” << endl; }

int main() { int a = 10; func(a); //调用第一个函数版本 func(10); //调用第二个函数版本

  1. system("pause");
  2. return 0;

}

  1. <a name="Y2wfK"></a>
  2. ### 类和对象
  3. <a name="NXubl"></a>
  4. ### 封装(*)
  5. C++面向对象的三大特性:封装、继承、多态
  6. <a name="mZP2G"></a>
  7. #### 封装的意义一
  8. 语法:class 类名{};<br />类中的属性和行为都称为“成员”<br />属性---成员属性 成员变量<br />行为---成员函数 成员方法
  9. ```cpp
  10. #include<iostream> //头文件
  11. #include<string>
  12. using namespace std;
  13. //设计一个圆类,求圆的周长
  14. //圆周长公式:2*PI*半径
  15. const double PI = 3.14;
  16. //class 代表设计一个类
  17. class Circle
  18. {
  19. //访问权限
  20. //公共权限
  21. public:
  22. //属性
  23. //半径
  24. int m_r;
  25. //行为
  26. //获取圆的周长
  27. double calculateZC()
  28. {
  29. return 2 * PI * m_r;
  30. }
  31. };
  32. int main()
  33. {
  34. //通过圆类 创建具体的圆(对象)
  35. Circle cl;
  36. //给圆对象的属性进行赋值
  37. cl.m_r = 10;
  38. cout << "圆的周长为:" << cl.calculateZC() << endl;
  39. system("pause");
  40. return 0;
  41. }
  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //设计一个学生类,可以给学生姓名和学号赋值,可以显示学生姓名和学号
  5. class Student
  6. {
  7. //访问权限
  8. //公共权限
  9. public:
  10. //属性
  11. //学生姓名和学号
  12. string Name;
  13. string Number;
  14. //行为
  15. void print()
  16. {
  17. cout << "学生姓名为:" << Name << endl;
  18. cout << "学生学号为:" << Number << endl;
  19. }
  20. };
  21. int main()
  22. {
  23. string name;
  24. cout << "请输入学生的姓名:" << endl;
  25. cin >> name;
  26. string number;
  27. cout << "请输入学生的学号:" << endl;
  28. cin >> number;
  29. //生成一个学生类
  30. Student st1;
  31. st1.Name = name;
  32. st1.Number = number;
  33. st1.print(name, number);
  34. system("pause");
  35. return 0;
  36. }

封装意义二

封装权限:
1)public 公共权限,类内可以访问,类外也可以访问;
2)protected保护权限,类内可以访问,类外不可以访问,儿子可以访问父亲的保护内容;
2)private私有权限,类内可以访问,类外不可以访问,儿子不可以访问父亲的私有内容。

  1. #include<iostream> //头文件
  2. #include<string>
  3. using namespace std;
  4. //设计一个学生类,可以给学生姓名和学号赋值,可以显示学生姓名和学号
  5. class Person
  6. {
  7. public:
  8. string name;
  9. protected:
  10. string car;
  11. private:
  12. int Password;
  13. public:
  14. void func()
  15. {
  16. name = "张三";
  17. car = "奔驰"; //类内可以访问
  18. Password = 123456; //类内可以访问
  19. }
  20. };
  21. int main()
  22. {
  23. Person pr;
  24. pr.name = "李四"; //类外仅可以访问公共权限
  25. system("pause");
  26. return 0;
  27. }

struct 和class的区别

C++中class和struct 的唯一区别在于默认权限不一样

  • srtuct:默认权限为公共权限
  • class:默认权限为私有权限

    封装-成员属性私有化

    优点:1)可以设置成员变量的读/写的权限;2)对于写可以检测数据的有效性 ```cpp class Person { public: //姓名 可写 void setName(string name) {
    1. m_Name = name;
    } //姓名 可读 string getname() {
    1. return m_Name;
    } //获取年龄 只读 int getAge() {
    1. m_Age = 0;
    2. return m_Age;
    } //设置情人 只写 void setlover(string lover) {
    1. m_Lover = lover;
    }

private: //姓名 可读可写 string m_Name; //年龄 只读 int m_Age; //情人 只写 string m_Lover; };

  1. <a name="v5Arm"></a>
  2. #### 封装-案例2
  3. - **在类中可以将另一个类作为成员**
  4. - **如将类与成员函数分开写,简化代码**
  5. 头文件:
  6. ```cpp
  7. #pragma once
  8. #include<iostream>
  9. //头文件中对类中成员进行声明
  10. class point
  11. {
  12. public:
  13. //成员函数声明
  14. //设置x
  15. void setX(int x);
  16. //获取x
  17. int getX();
  18. //设置y
  19. void setY(int y);
  20. //获取y
  21. int getY();
  22. private:
  23. //成员变量声明
  24. int m_X;
  25. int m_Y;
  26. };
  1. #pragma once
  2. #include<iostream>
  3. #include"point.h"
  4. class circle
  5. {
  6. public:
  7. //设置半径
  8. void setR(int r);
  9. //获取半径
  10. int getR();
  11. //设置圆心
  12. void setCenter(point center);
  13. //获取圆心
  14. point getCenter();
  15. private:
  16. //半径
  17. int m_R;
  18. //圆心
  19. point m_Center;
  20. };

源文件:

  1. #include<iostream> //头文件
  2. #include<string>
  3. #include"circle.h"
  4. #include"point.h"
  5. using namespace std;
  6. void isInCircle(circle& c, point& p)
  7. {
  8. //计算距离平方
  9. int distance =
  10. (c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) +
  11. (c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY());
  12. //计算半径平方
  13. int rdistance = c.getR() * c.getR();
  14. //判断位置关系
  15. if (distance == rdistance)
  16. {
  17. cout << "点在圆上" << endl;
  18. }
  19. else if (distance > rdistance)
  20. {
  21. cout << "点在圆外" << endl;
  22. }
  23. else
  24. {
  25. cout << "点在圆内" << endl;
  26. }
  27. }
  28. int main()
  29. {
  30. circle c;
  31. point p;
  32. p.setX(10);
  33. p.setY(10);
  34. c.setR(10);
  35. c.setCenter(p);
  36. isInCircle(c, p);
  37. system("pause");
  38. return 0;
  39. }
  1. #include"point.h"
  2. #include<iostream>
  3. void point::setX(int x)
  4. {
  5. m_X = x;
  6. }
  7. int point::getX()
  8. {
  9. return m_X;
  10. }
  11. void point::setY(int y)
  12. {
  13. m_Y = y;
  14. }
  15. int point::getY()
  16. {
  17. return m_Y;
  18. }
  1. #include"circle.h"
  2. #include<iostream>
  3. void circle::setR(int r)
  4. {
  5. m_R = r;
  6. }
  7. int circle::getR()
  8. {
  9. return m_R;
  10. }
  11. void circle::setCenter(point center)
  12. {
  13. m_Center = center;
  14. }
  15. point circle::getCenter()
  16. {
  17. return m_Center;
  18. }

对象初始化和清理(?)

构造函数和析构函数

两个函数将会被编译器自动调用

  • 构造函数:作用在于创建对象时为对象的成员属性赋值,语法: 类名(){}
  • 析构函数:主要作用在于对象销毁前系统自动调用,语法:~类名(){} ```cpp

    include //头文件

    include

    using namespace std;

//对象的初始化和清理 //1、构造函数 进行初始化操作 class Person { public: //1、构造函数 //没有返回值 不用写void //函数名 与类名相同 //构造函数可以有参数,可以发生重载 //创建对象的时候,构造函数会自动调用,而且只调用一次 Person() { cout << “Person构造函数的调用” << endl; } //2、析构函数 进行清理的操作 //没有返回值 不用写void //函数名和类名相同 在名称前加~ //析构函数不可以有参数的,不可以发生重载 //对象销毁前 会自动调用析构函数 而且只调用一次 ~Person() { cout << “Person析构函数的调用” << endl; } };

void test01() { Person p; // 在栈上的数据,在test01执行完毕后,释放这个对象 }

int main() { test01();//调用test01函数

  1. system("pause");
  2. return 0;

}

  1. <a name="buhdj"></a>
  2. #### 构造函数的分类及应用
  3. ```cpp
  4. #include<iostream>
  5. #include<string>
  6. using namespace std;
  7. //1、构造函数分类
  8. //按照参数分类分为有参和无参构造 午餐又称为默认构造函数
  9. //按照类型分类分为 普通构造和拷贝构造
  10. class Person
  11. {
  12. public:
  13. //无参(默认)构造函数
  14. Person()
  15. {
  16. cout << "无参构造函数!" << endl;
  17. }
  18. //有参构造函数
  19. Person(int a)
  20. {
  21. age = a;
  22. cout << "有参构造函数!" << endl;
  23. }
  24. //拷贝构造函数
  25. Person(const Person &P) //注意形参的写法
  26. {
  27. //将传入的人身上的所有属性,拷贝到我身上
  28. age = P.age;
  29. cout << "拷贝函数!" << endl;
  30. }
  31. //析构函数
  32. ~Person()
  33. {
  34. cout << "析构函数!" << endl;
  35. }
  36. public:
  37. int age;
  38. };
  39. void test02()
  40. {
  41. //1、括号法
  42. Person p1; //默认构造函数调用
  43. Person p2(10); // 有参构造函数
  44. Person p3(p2); //拷贝构造函数调用
  45. //注意事项
  46. //调用默认函数时,不要加()
  47. //因为下面这行代码,编译器会认为时一个函数的声明
  48. //2、显示法
  49. //Person p1;
  50. //Person p2 = Person(10); //有参构造
  51. //Person p3 = Person(p2); //拷贝函数
  52. //注意事项2
  53. //不要利用拷贝构造函数,初始化匿名对象
  54. //3、隐式转换法
  55. //Person p4 = 10; //相当于写了 Person p4 = Person(10),有参构造
  56. //Person p5 = p4; //拷贝构造
  57. }
  58. int main()
  59. {
  60. test02();
  61. system("pause");
  62. return 0;
  63. }

拷贝构造函数调用时机

image.png

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

构造函数的调用规则

image.png

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //构造函数的调用规则
  5. //1、创建一个类,C++编译器会给每个类都添加至少3个函数
  6. //默认构造(空实现)
  7. // 析构函数(空实现)
  8. //拷贝构造(值拷贝)
  9. class Person
  10. {
  11. public:
  12. Person()
  13. {
  14. cout << "Person的默认构造函数调用" << endl;
  15. }
  16. Person(int age)
  17. {
  18. cout << "Person的有参构造函数调用" << endl;
  19. m_Age = age;
  20. }
  21. Person(const Person& p)
  22. {
  23. cout << "Person的拷贝造函数调用" << endl;
  24. m_Age = p.m_Age;
  25. }
  26. ~Person()
  27. {
  28. cout << "" << endl;
  29. }
  30. int m_Age;
  31. };
  32. //2、
  33. //如果有了有参构造函数,编译器就不再提供默认构造函数,但是会提供拷贝构造函数
  34. //如果我们写了拷贝构造函数,编译器就不再提供其他构造函数
  35. void test01()
  36. {
  37. Person p;
  38. p.m_Age = 18;
  39. Person p2(p);
  40. cout << "p2的年龄为:" << p2.m_Age << endl;
  41. }
  42. int main()
  43. {
  44. test01();
  45. system("pause");
  46. return 0;
  47. }

深拷贝和浅拷贝

image.png
浅拷贝带来的问题就是堆区的内存重复释放,需要利用深拷贝的问题来进行解决

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //深拷贝与浅拷贝
  5. class Person
  6. {
  7. public:
  8. Person()
  9. {
  10. cout << "调用默认构造函数" << endl;
  11. }
  12. Person(int age, int height)
  13. {
  14. m_Age = age;
  15. m_Height = new int(height);
  16. cout << "Person的有参构造函数调用" << endl;
  17. }
  18. //自己实现拷贝构造函数 解决浅拷贝带来的问题
  19. Person()
  20. {
  21. cout << "Person kaobei hanshu s" << endl;
  22. }
  23. ~Person()
  24. {
  25. //析构代码,将堆区开辟的数据做释放操作
  26. if (m_Height != NULL)
  27. {
  28. delete m_Height;
  29. m_Height = NULL;
  30. }
  31. cout << "Person的析构函数调用" << endl;
  32. }
  33. int m_Age; //年龄
  34. int* m_Height; //身高
  35. };
  36. int main()
  37. {
  38. test01();
  39. system("pause");
  40. return 0;
  41. }

初始化列表

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //初始化列表
  5. class Person
  6. {
  7. public:
  8. //传统初始化操作
  9. //int m_A;
  10. //int m_B;
  11. //int m_C;
  12. //初始化列表初始化属性
  13. Person(int a, int b, int c) :m_A(a),m_B(b),m_C(c)
  14. {
  15. }
  16. int m_A;
  17. int m_B;
  18. int m_C;
  19. };
  20. int main()
  21. {
  22. Person p(30, 20, 10);
  23. cout << "m_A:" << p.m_A << endl;
  24. cout << "m_B" << p.m_B << endl;
  25. cout << "m_C:" << p.m_C << endl;
  26. system("pause");
  27. return 0;
  28. }

类对象作为类成员

C++类中的成员可以作为另一个类中的对象,我们称之为对象成员

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //类对象作为类成员
  5. //手机类
  6. class Phone
  7. {
  8. public:
  9. Phone(string pName)
  10. {
  11. m_PName = pName;
  12. cout << "phone的构造函数调用" << endl;
  13. }
  14. ~Phone()
  15. {
  16. cout << "Phone的析构函数调用" << endl;
  17. }
  18. string m_PName;
  19. };
  20. class Person
  21. {
  22. public:
  23. //Phone m_Phone = pName 隐式转化法
  24. Person(string name, string pName) :m_Name(name), m_Phone(pName)
  25. {
  26. cout << "Person的构造函数调用" << endl;
  27. }
  28. ~Person()
  29. {
  30. cout << "Person的析构函数调用" << endl;
  31. }
  32. //姓名
  33. string m_Name;
  34. //手机
  35. Phone m_Phone;
  36. };
  37. //当其他类对象作为本类成员,构造时先构造对象,在构造自身,析构的顺序与构造相反
  38. void test01()
  39. {
  40. Person p("张三","苹果");
  41. cout<<p.m_Name << "拿着" << p.m_Phone.m_PName << endl;
  42. }
  43. int main()
  44. {
  45. test01();
  46. system("pause");
  47. return 0;
  48. }

静态成员

image.png

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //静态成员
  5. class Person
  6. {
  7. public:
  8. static int m_A;
  9. //静态成员变量也有访问权限
  10. private:
  11. static int m_B;};
  12. int Person::m_A = 100;
  13. void test01()
  14. {
  15. //静态成员变量,不属于某个对象上,所有对象都可以共享同一份数据
  16. //因此静态成员变量有两种访问方式
  17. //1、通过对象访问
  18. Person p1;
  19. cout << p1.m_A << endl;
  20. //2、通过类名进行访问
  21. cout << Person::m_A << endl;
  22. }
  23. int main()
  24. {
  25. test01();
  26. system("pause");
  27. return 0;
  28. }

C++对象模型和this指针

this指针概念

image.png

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Person
  5. {
  6. public:
  7. Person(int age)
  8. {
  9. this->age = age; //this指针指向被调用成员函数的所属对象
  10. }
  11. Person& PersonAddAge(Person p)
  12. {
  13. Person p1(10);
  14. this->age += p1.age;
  15. return *this;
  16. }
  17. int age;
  18. };
  19. //1、解决名称冲突
  20. void test01()
  21. {
  22. Person p1(18);
  23. cout << "p1的年龄为:" << p1.age << endl;
  24. }
  25. //2、返回对象本身*this
  26. void test02()
  27. {
  28. Person p1(10);
  29. Person p2(10);
  30. p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
  31. cout << "p2的年龄为:" << p2.age << endl;
  32. }
  33. int main()
  34. {
  35. test01();
  36. test02();
  37. system("pause");
  38. return 0;
  39. }

空指针访问成员函数

image.png

Const修饰成员函数

image.png

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //空指针调用成员函数
  5. class Person {
  6. public:
  7. Person() {
  8. m_A = 0;
  9. m_B = 0;
  10. }
  11. //this指针的本质是一个指针常量,指针的指向不可修改
  12. //如果想让指针指向的值也不可以修改,需要声明常函数
  13. void ShowPerson() const {
  14. //const Type* const pointer;
  15. //this = NULL; //不能修改指针的指向 Person* const this;
  16. //this->mA = 100; //但是this指针指向的对象的数据是可以修改的
  17. //const修饰成员函数,表示指针指向的内存空间的数据不能修改,除了mutable修饰的变量
  18. this->m_B = 100;
  19. }
  20. void MyFunc() const {
  21. //mA = 10000;
  22. }
  23. public:
  24. int m_A;
  25. mutable int m_B; //可修改 可变的
  26. };
  27. //const修饰对象 常对象
  28. void test01() {
  29. const Person person; //常量对象
  30. cout << person.m_A << endl;
  31. //person.mA = 100; //常对象不能修改成员变量的值,但是可以访问
  32. person.m_B = 100; //但是常对象可以修改mutable修饰成员变量
  33. //常对象访问成员函数
  34. person.MyFunc(); //常对象不能调用const的函数
  35. }
  36. int main() {
  37. test01();
  38. system("pause");
  39. return 0;
  40. }

友元

生活中你的家有客厅(Public),有你的卧室(Private)
客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去
但是呢,你也可以允许你的好闺蜜好基友进去。
在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术
友元的目的就是让一个函数或者类 访问另一个类中私有成员
友元的关键字为 ==friend==

全局函数做友元

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Building
  5. {
  6. //告诉编译器 goodGay全局函数 是 Building类的好朋友,可以访问类中的私有内容
  7. friend void goodGay(Building* building);
  8. public:
  9. Building()
  10. {
  11. this->m_SittingRoom = "客厅";
  12. this->m_BedRoom = "卧室";
  13. }
  14. public:
  15. string m_SittingRoom; //客厅
  16. private:
  17. string m_BedRoom; //卧室
  18. };
  19. void goodGay(Building* building)
  20. {
  21. cout << "好基友正在访问: " << building->m_SittingRoom << endl;
  22. cout << "好基友正在访问: " << building->m_BedRoom << endl;
  23. }
  24. void test01()
  25. {
  26. Building b;
  27. goodGay(&b);
  28. }
  29. int main() {
  30. test01();
  31. system("pause");
  32. return 0;
  33. }

类做友元

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Building;
  5. class goodGay
  6. {
  7. public:
  8. goodGay();
  9. void visit();
  10. private:
  11. Building* building;
  12. };
  13. class Building
  14. {
  15. //告诉编译器 goodGay类是Building类的好朋友,可以访问到Building类中私有内容
  16. friend class goodGay;
  17. public:
  18. Building();
  19. public:
  20. string m_SittingRoom; //客厅
  21. private:
  22. string m_BedRoom;//卧室
  23. };
  24. Building::Building() //类内定义,类外实现
  25. {
  26. this->m_SittingRoom = "客厅";
  27. this->m_BedRoom = "卧室";
  28. }
  29. goodGay::goodGay()
  30. {
  31. building = new Building;
  32. }
  33. void goodGay::visit()
  34. {
  35. cout << "好基友正在访问" << building->m_SittingRoom << endl;
  36. cout << "好基友正在访问" << building->m_BedRoom << endl;
  37. }
  38. void test01()
  39. {
  40. goodGay gg;
  41. gg.visit();
  42. }
  43. int main() {
  44. test01();
  45. system("pause");
  46. return 0;
  47. }

成员函数做友元

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Building;
  5. class goodGay
  6. {
  7. public:
  8. goodGay();
  9. void visit(); //只让visit函数作为Building的好朋友,可以发访问Building中私有内容
  10. void visit2();
  11. private:
  12. Building* building;
  13. };
  14. class Building
  15. {
  16. //告诉编译器 goodGay类中的visit成员函数 是Building好朋友,可以访问私有内容
  17. friend void goodGay::visit();
  18. public:
  19. Building();
  20. public:
  21. string m_SittingRoom; //客厅
  22. private:
  23. string m_BedRoom;//卧室
  24. };
  25. Building::Building()
  26. {
  27. this->m_SittingRoom = "客厅";
  28. this->m_BedRoom = "卧室";
  29. }
  30. goodGay::goodGay()
  31. {
  32. building = new Building;
  33. }
  34. void goodGay::visit()
  35. {
  36. cout << "好基友正在访问" << building->m_SittingRoom << endl;
  37. cout << "好基友正在访问" << building->m_BedRoom << endl;
  38. }
  39. void goodGay::visit2()
  40. {
  41. cout << "好基友正在访问" << building->m_SittingRoom << endl;
  42. //cout << "好基友正在访问" << building->m_BedRoom << endl;
  43. }
  44. void test01()
  45. {
  46. goodGay gg;
  47. gg.visit();
  48. }
  49. int main() {
  50. test01();
  51. system("pause");
  52. return 0;
  53. }

运算符重载

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

加号运算符重载

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

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Person {
  5. public:
  6. Person() {};
  7. Person(int a, int b)
  8. {
  9. this->m_A = a;
  10. this->m_B = b;
  11. }
  12. //1、成员函数实现 + 号运算符重载
  13. Person operator+(const Person& p) {
  14. Person temp;
  15. temp.m_A = this->m_A + p.m_A;
  16. temp.m_B = this->m_B + p.m_B;
  17. return temp;
  18. }
  19. public:
  20. int m_A;
  21. int m_B;
  22. };
  23. //2、全局函数实现 + 号运算符重载
  24. //Person operator+(const Person& p1, const Person& p2) {
  25. // Person temp(0, 0);
  26. // temp.m_A = p1.m_A + p2.m_A;
  27. // temp.m_B = p1.m_B + p2.m_B;
  28. // return temp;
  29. //}
  30. //运算符重载 可以发生函数重载(形参类型不同,实现函数重载)
  31. Person operator+(const Person& p2, int val)
  32. {
  33. Person temp;
  34. temp.m_A = p2.m_A + val;
  35. temp.m_B = p2.m_B + val;
  36. return temp;
  37. }
  38. void test() {
  39. Person p1(10, 10);
  40. Person p2(20, 20);
  41. //成员函数方式
  42. Person p3 = p2 + p1; //相当于 p2.operaor+(p1)
  43. cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;
  44. Person p4 = p3 + 10; //相当于 operator+(p3,10)
  45. cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;
  46. }
  47. int main() {
  48. test();
  49. system("pause");
  50. return 0;
  51. }

PS:总结1:对于内置的数据类型的表达式的的运算符是不可能改变的
总结2:不要滥用运算符重载

左移运算符重载(?)

作用:可以输出自定义数据类型
通常不利用成员函数重载左移运算符

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Person
  5. {
  6. friend ostream& operator<<(ostream& out, Person& p);
  7. public:
  8. Person(int a, int b)
  9. {
  10. this->m_A = a;
  11. this->m_B = b;
  12. }
  13. //成员函数 实现不了 p << cout 不是我们想要的效果
  14. //void operator<<(Person& p){
  15. //}
  16. private:
  17. int m_A;
  18. int m_B;
  19. };
  20. //全局函数实现左移重载
  21. //ostream对象只能有一个
  22. ostream& operator<<(ostream& out, Person& p) {
  23. out << "a:" << p.m_A << " b:" << p.m_B;
  24. return out;
  25. }
  26. void test() {
  27. Person p1(10, 20);
  28. cout << p1 << "hello world" << endl; //链式编程
  29. }
  30. int main() {
  31. test();
  32. system("pause");
  33. return 0;
  34. }

总结:重载左移运算符配合友元可以实现输出自定义数据类型

递增运算符重载

作用: 通过重载递增运算符,实现自己的整型数据

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class MyInteger {
  5. friend ostream& operator<<(ostream& out, MyInteger myint);
  6. public:
  7. MyInteger() {
  8. m_Num = 0;
  9. }
  10. //前置++
  11. MyInteger& operator++() {
  12. //先++
  13. m_Num++;
  14. //再返回
  15. return *this;
  16. }
  17. //后置++
  18. MyInteger operator++(int) {
  19. //先返回
  20. MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
  21. m_Num++;
  22. return temp;
  23. }
  24. private:
  25. int m_Num;
  26. };
  27. ostream& operator<<(ostream& out, MyInteger myint) {
  28. out << myint.m_Num;
  29. return out;
  30. }
  31. //前置++ 先++ 再返回
  32. void test01() {
  33. MyInteger myInt;
  34. cout << ++myInt << endl;
  35. cout << myInt << endl;
  36. }
  37. //后置++ 先返回 再++
  38. void test02() {
  39. MyInteger myInt;
  40. cout << myInt++ << endl;
  41. cout << myInt << endl;
  42. }
  43. int main() {
  44. test01();
  45. //test02();
  46. system("pause");
  47. return 0;
  48. }

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

赋值运算符重载

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

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符 operator=, 对属性进行值拷贝

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

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Person
  5. {
  6. public:
  7. Person(int age)
  8. {
  9. //将年龄数据开辟到堆区
  10. m_Age = new int(age);
  11. }
  12. //重载赋值运算符
  13. Person& operator=(Person &p)
  14. {
  15. if (m_Age != NULL)
  16. {
  17. delete m_Age;
  18. m_Age = NULL;
  19. }
  20. //编译器提供的代码是浅拷贝
  21. //m_Age = p.m_Age;
  22. //提供深拷贝 解决浅拷贝的问题
  23. m_Age = new int(*p.m_Age);
  24. //返回自身
  25. return *this;
  26. }
  27. ~Person()
  28. {
  29. if (m_Age != NULL)
  30. {
  31. delete m_Age;
  32. m_Age = NULL;
  33. }
  34. }
  35. //年龄的指针
  36. int *m_Age;
  37. };
  38. void test01()
  39. {
  40. Person p1(18);
  41. Person p2(20);
  42. Person p3(30);
  43. p3 = p2 = p1; //赋值操作
  44. cout << "p1的年龄为:" << *p1.m_Age << endl;
  45. cout << "p2的年龄为:" << *p2.m_Age << endl;
  46. cout << "p3的年龄为:" << *p3.m_Age << endl;
  47. }
  48. int main() {
  49. test01();
  50. //int a = 10;
  51. //int b = 20;
  52. //int c = 30;
  53. //c = b = a;
  54. //cout << "a = " << a << endl;
  55. //cout << "b = " << b << endl;
  56. //cout << "c = " << c << endl;
  57. system("pause");
  58. return 0;
  59. }

疑问:1)怎样区分栈区数据和堆区数据;2)深浅拷贝的作用和区别

关系运算符重载

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

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Person
  5. {
  6. public:
  7. Person(string name, int age)
  8. {
  9. this->m_Name = name;
  10. this->m_Age = age;
  11. };
  12. bool operator==(Person & p)
  13. {
  14. if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
  15. {
  16. return true;
  17. }
  18. else
  19. {
  20. return false;
  21. }
  22. }
  23. bool operator!=(Person & p)
  24. {
  25. if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
  26. {
  27. return false;
  28. }
  29. else
  30. {
  31. return true;
  32. }
  33. }
  34. string m_Name;
  35. int m_Age;
  36. };
  37. void test01()
  38. {
  39. //int a = 0;
  40. //int b = 0;
  41. Person a("孙悟空", 18);
  42. Person b("孙悟空", 18);
  43. if (a == b)
  44. {
  45. cout << "a和b相等" << endl;
  46. }
  47. else
  48. {
  49. cout << "a和b不相等" << endl;
  50. }
  51. if (a != b)
  52. {
  53. cout << "a和b不相等" << endl;
  54. }
  55. else
  56. {
  57. cout << "a和b相等" << endl;
  58. }
  59. }
  60. int main() {
  61. test01();
  62. system("pause");
  63. return 0;
  64. }

函数调用运算符重载

  • 函数调用运算符 () 也可以重载
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法,非常灵活 ```cpp

    include

    include

    using namespace std;

class MyPrint { public: void operator()(string text) { cout << text << endl; }

}; void test01() { //重载的()操作符 也称为仿函数 MyPrint myFunc; myFunc(“hello world”); }

class MyAdd { public: int operator()(int v1, int v2) { return v1 + v2; } };

void test02() { MyAdd add; int ret = add(10, 10); cout << “ret = “ << ret << endl;

  1. //匿名对象调用
  2. cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;

}

int main() {

  1. test01();
  2. test02();
  3. system("pause");
  4. return 0;

}

  1. <a name="QUZ5y"></a>
  2. ### 继承(*)
  3. <a name="g4E5u"></a>
  4. #### 基本语法
  5. 作用:减少重复代码
  6. ```cpp
  7. #include<iostream>
  8. #include<string>
  9. using namespace std;
  10. //公共页面
  11. class BasePage
  12. {
  13. public:
  14. void header()
  15. {
  16. cout << "首页、公开课、登录、注册...(公共头部)" << endl;
  17. }
  18. void footer()
  19. {
  20. cout << "帮助中心、交流合作、站内地图...(公共底部)" << endl;
  21. }
  22. void left()
  23. {
  24. cout << "Java,Python,C++...(公共分类列表)" << endl;
  25. }
  26. };
  27. //Java页面
  28. class Java : public BasePage //语法
  29. {
  30. public:
  31. void content()
  32. {
  33. cout << "JAVA学科视频" << endl;
  34. }
  35. };
  36. //Python页面
  37. class Python : public BasePage
  38. {
  39. public:
  40. void content()
  41. {
  42. cout << "Python学科视频" << endl;
  43. }
  44. };
  45. //C++页面
  46. class CPP : public BasePage
  47. {
  48. public:
  49. void content()
  50. {
  51. cout << "C++学科视频" << endl;
  52. }
  53. };
  54. void test01()
  55. {
  56. //Java页面
  57. cout << "Java下载视频页面如下: " << endl;
  58. Java ja;
  59. ja.header();
  60. ja.footer();
  61. ja.left();
  62. ja.content();
  63. cout << "--------------------" << endl;
  64. //Python页面
  65. cout << "Python下载视频页面如下: " << endl;
  66. Python py;
  67. py.header();
  68. py.footer();
  69. py.left();
  70. py.content();
  71. cout << "--------------------" << endl;
  72. //C++页面
  73. cout << "C++下载视频页面如下: " << endl;
  74. CPP cp;
  75. cp.header();
  76. cp.footer();
  77. cp.left();
  78. cp.content();
  79. }
  80. int main() {
  81. test01();
  82. system("pause");
  83. return 0;
  84. }

继承方式

继承的语法:class 子类 : 继承方式 父类
继承方式一共有三种:

  • 公共继承
  • 保护继承
  • 私有继承

image.png

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Base1
  5. {
  6. public:
  7. int m_A;
  8. protected:
  9. int m_B;
  10. private:
  11. int m_C;
  12. };
  13. //公共继承
  14. class Son1 :public Base1
  15. {
  16. public:
  17. void func()
  18. {
  19. m_A; //可访问 public权限
  20. m_B; //可访问 protected权限
  21. //m_C; //不可访问
  22. }
  23. };
  24. void myClass()
  25. {
  26. Son1 s1;
  27. s1.m_A; //其他类只能访问到公共权限
  28. }
  29. //保护继承
  30. class Base2
  31. {
  32. public:
  33. int m_A;
  34. protected:
  35. int m_B;
  36. private:
  37. int m_C;
  38. };
  39. class Son2 :protected Base2
  40. {
  41. public:
  42. void func()
  43. {
  44. m_A; //可访问 protected权限
  45. m_B; //可访问 protected权限
  46. //m_C; //不可访问
  47. }
  48. };
  49. void myClass2()
  50. {
  51. Son2 s;
  52. //s.m_A; //不可访问
  53. }
  54. //私有继承
  55. class Base3
  56. {
  57. public:
  58. int m_A;
  59. protected:
  60. int m_B;
  61. private:
  62. int m_C;
  63. };
  64. class Son3 :private Base3
  65. {
  66. public:
  67. void func()
  68. {
  69. m_A; //可访问 private权限
  70. m_B; //可访问 private权限
  71. //m_C; //不可访问
  72. }
  73. };
  74. class GrandSon3 :public Son3
  75. {
  76. public:
  77. void func()
  78. {
  79. //Son3是私有继承,所以继承Son3的属性在GrandSon3中都无法访问到
  80. //m_A;
  81. //m_B;
  82. //m_C;
  83. }
  84. };

继承中的对象模型

父类中私有成员也是被子类继承下去了,只是由编译器给隐藏后访问不到

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Base
  5. {
  6. public:
  7. int m_A;
  8. protected:
  9. int m_B;
  10. private:
  11. int m_C; //私有成员只是被隐藏了,但是还是会继承下去
  12. };
  13. //公共继承
  14. class Son :public Base
  15. {
  16. public:
  17. int m_D;
  18. };
  19. void test01()
  20. {
  21. //16
  22. //父类中所有非静态成员属性都会倍子类继承下去
  23. //父类中私有成员属性被编译器隐藏了,因此访问不到,但确实被继承下去了
  24. cout << "sizeof Son = " << sizeof(Son) << endl;
  25. }
  26. int main() {
  27. test01();
  28. system("pause");
  29. return 0;
  30. }

继承中构造和析构顺序

子类继承父类后,当创建子类对象,也会调用父类的构造函数
问题:父类和子类的构造和析构顺序是谁先谁后?

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Base
  5. {
  6. public:
  7. Base()
  8. {
  9. cout << "Base构造函数!" << endl;
  10. }
  11. ~Base()
  12. {
  13. cout << "Base析构函数!" << endl;
  14. }
  15. };
  16. class Son : public Base
  17. {
  18. public:
  19. Son()
  20. {
  21. cout << "Son构造函数!" << endl;
  22. }
  23. ~Son()
  24. {
  25. cout << "Son析构函数!" << endl;
  26. }
  27. };
  28. void test01()
  29. {
  30. //继承中 先调用父类构造函数,再调用子类构造函数,析构顺序与构造相反
  31. Son s;
  32. }
  33. int main() {
  34. test01();
  35. system("pause");
  36. return 0;
  37. }

结论:继承中 先调用父类构造函数,再调用子类构造函数,析构顺序与构造相反。

继承中同名成员处理方式

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Base {
  5. public:
  6. Base()
  7. {
  8. m_A = 100;
  9. }
  10. void func()
  11. {
  12. cout << "Base - func()调用" << endl;
  13. }
  14. void func(int a)
  15. {
  16. cout << "Base - func(int a)调用" << endl;
  17. }
  18. public:
  19. int m_A;
  20. };
  21. class Son : public Base {
  22. public:
  23. Son()
  24. {
  25. m_A = 200;
  26. }
  27. //当子类与父类拥有同名的成员函数,子类会隐藏父类中所有版本的同名成员函数
  28. //如果想访问父类中被隐藏的同名成员函数,需要加父类的作用域
  29. void func()
  30. {
  31. cout << "Son - func()调用" << endl;
  32. }
  33. public:
  34. int m_A;
  35. };
  36. void test01()
  37. {
  38. Son s;
  39. cout << "Son下的m_A = " << s.m_A << endl;
  40. cout << "Base下的m_A = " << s.Base::m_A << endl;//添加父类的作用域,实现父类中同名成员的调用
  41. s.func();
  42. s.Base::func();
  43. s.Base::func(10);
  44. }
  45. int main() {
  46. test01();
  47. system("pause");
  48. return EXIT_SUCCESS;
  49. }

总结:

  1. 子类对象可以直接访问到子类中同名成员
  2. 子类对象加作用域可以访问到父类同名成员
  3. 当子类与父类拥有同名的成员函数,子类会隐藏父类中同名成员函数,加作用域可以访问到父类中同名函数

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

    问题:继承中同名的静态成员在子类对象上如何进行访问?
    静态成员和非静态成员出现同名,处理方式一致
  • 访问子类同名成员 直接访问即可
  • 访问父类同名成员 需要加作用域 ```cpp

    include

    include

    using namespace std;

class Base { public: static void func() { cout << “Base - static void func()” << endl; } static void func(int a) { cout << “Base - static void func(int a)” << endl; }

  1. static int m_A;

};

int Base::m_A = 100;

class Son : public Base { public: static void func() { cout << “Son - static void func()” << endl; } static int m_A; };

int Son::m_A = 200;

//同名成员属性 void test01() { //通过对象访问 cout << “通过对象访问: “ << endl; Son s; cout << “Son 下 m_A = “ << s.m_A << endl; cout << “Base 下 m_A = “ << s.Base::m_A << endl;

  1. //通过类名访问
  2. cout << "通过类名访问: " << endl;
  3. cout << "Son 下 m_A = " << Son::m_A << endl;
  4. //第一个::代表通过类名方式访问,第二个::代表访问父类作用域下
  5. cout << "Base 下 m_A = " << Son::Base::m_A << endl;

}

//同名成员函数 void test02() { //通过对象访问 cout << “通过对象访问: “ << endl; Son s; s.func(); s.Base::func();

  1. cout << "通过类名访问: " << endl;
  2. Son::func();
  3. Son::Base::func();
  4. //出现同名,子类会隐藏掉父类中所有同名成员函数,需要加作作用域访问
  5. Son::Base::func(100);

} int main() {

  1. //test01();
  2. test02();
  3. system("pause");
  4. return 0;

}

  1. **总结:同名静态成员处理方式和非静态处理方式一样,只不过有两种访问的方式(通过对象 通过类名)**
  2. <a name="jQJNr"></a>
  3. #### 多继承语法(不建议使用)
  4. C++允许**一个类继承多个类**<br />语法:class 子类 :继承方式 父类1 继承方式 父类2...<br />多继承可能会引发父类中有同名成员出现,需要加作用域区分<br />**C++实际开发中不建议用多继承**
  5. ```cpp
  6. #include<iostream>
  7. #include<string>
  8. using namespace std;
  9. class Base1 {
  10. public:
  11. Base1()
  12. {
  13. m_A = 100;
  14. }
  15. public:
  16. int m_A;
  17. };
  18. class Base2 {
  19. public:
  20. Base2()
  21. {
  22. m_A = 200; //开始是m_B 不会出问题,但是改为mA就会出现不明确
  23. }
  24. public:
  25. int m_A;
  26. };
  27. //语法:class 子类:继承方式 父类1 ,继承方式 父类2
  28. class Son : public Base2, public Base1
  29. {
  30. public:
  31. Son()
  32. {
  33. m_C = 300;
  34. m_D = 400;
  35. }
  36. public:
  37. int m_C;
  38. int m_D;
  39. };
  40. //多继承容易产生成员同名的情况
  41. //通过使用类名作用域可以区分调用哪一个基类的成员
  42. void test01()
  43. {
  44. Son s;
  45. cout << "sizeof Son = " << sizeof(s) << endl;
  46. cout << s.Base1::m_A << endl;
  47. cout << s.Base2::m_A << endl;
  48. }
  49. int main() {
  50. test01();
  51. system("pause");
  52. return 0;
  53. }

总结: 多继承中如果父类中出现了同名情况,子类使用时候要加作用域

菱形继承问题及解决方法(用的比较少)

菱形继承概念:
两个派生类继承同一个基类
又有某个类同时继承者两个派生类
这种继承被称为菱形继承,或者钻石继承

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. class Animal
  5. {
  6. public:
  7. int m_Age;
  8. };
  9. //继承前加virtual关键字后,变为虚继承
  10. //此时公共的父类Animal称为虚基类
  11. class Sheep : virtual public Animal {};
  12. class Tuo : virtual public Animal {};
  13. class SheepTuo : public Sheep, public Tuo {};
  14. void test01()
  15. {
  16. SheepTuo st;
  17. st.Sheep::m_Age = 100;
  18. st.Tuo::m_Age = 200;
  19. //当菱形继承,两个父类拥有相同数据,需要加以作用域区分
  20. cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl;
  21. cout << "st.Tuo::m_Age = " << st.Tuo::m_Age << endl;
  22. //利用虚继承解决同时继承两份数据的情况
  23. cout << "st.m_Age = " << st.m_Age << endl;
  24. }
  25. int main() {
  26. test01();
  27. system("pause");
  28. return 0;
  29. }

总结:

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

    多态(*)

    多态基本语法

    多态是C++面向对象三大特性之一
    多态分为两类

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

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

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

  • 静态多态的函数地址早绑定 - 编译阶段确定函数地址
  • 动态多态的函数地址晚绑定 - 运行阶段确定函数地址 ```cpp

    include

    include

    using namespace std;

class Animal { public: //Speak函数就是虚函数 //函数前面加上virtual关键字,变成虚函数,那么编译器在编译的时候就不能确定函数调用了。 virtual void speak() { cout << “动物在说话” << endl; } };

class Cat :public Animal { public: //函数重写 函数返回值 函数名 参数列表 完全相同 void speak() { cout << “小猫在说话” << endl; } };

class Dog :public Animal { public:

  1. void speak()
  2. {
  3. cout << "小狗在说话" << endl;
  4. }

}; //我们希望传入什么对象,那么就调用什么对象的函数 //如果函数地址在编译阶段就能确定,那么静态联编 //如果函数地址在运行阶段才能确定,就是动态联编

void DoSpeak(Animal& animal) //通过父类的指针实现 { animal.speak(); } // //多态满足条件: //1、有继承关系 //2、子类重写父类中的虚函数 //多态使用: //父类指针或引用指向子类对象

void test01() { Cat cat; DoSpeak(cat);

  1. Dog dog;
  2. DoSpeak(dog);

}

int main() {

  1. test01();
  2. system("pause");
  3. return 0;

}

  1. 总结:<br />多态满足条件:
  2. - 有继承关系
  3. - 子类重写父类中的虚函数
  4. 多态使用条件:
  5. - 父类指针或引用指向子类对象
  6. 重写:函数返回值类型 函数名 参数列表 完全一致称为重写
  7. <a name="InYAY"></a>
  8. #### 多态原理剖析
  9. <a name="tV9R4"></a>
  10. #### 多态案例一
  11. ```cpp
  12. #include<iostream>
  13. #include<string>
  14. using namespace std;
  15. class Calculator
  16. {
  17. public:
  18. int getResult(string oper)
  19. {
  20. if (oper == "+")
  21. {
  22. return m_Num1 + m_Num2;
  23. }
  24. else if (oper == "-")
  25. {
  26. return m_Num1 - m_Num2;
  27. }
  28. else if (oper == "*")
  29. {
  30. return m_Num1 * m_Num2;
  31. }
  32. }
  33. //如果想扩展新的功能,需要修改源码
  34. //在真实开发中,提倡 开闭原则
  35. //开闭原则:对扩展开放,对修改关闭
  36. int m_Num1; //操作数1
  37. int m_Num2; //操作数2
  38. };
  39. //利用多态实现计算器
  40. //多态优点:
  41. //1、组织结构清晰
  42. //2、可读性强
  43. //3、有利于前期和后期的扩展和维护
  44. class AbstractCalculator : public Calculator
  45. {
  46. public:
  47. virtual int getResult()
  48. {
  49. return 0;
  50. }
  51. int m_Num1;
  52. int m_Num2;
  53. };
  54. //加法计算器类
  55. class AddCalculator : public AbstractCalculator
  56. {
  57. int getResult()
  58. {
  59. return m_Num1 + m_Num2;
  60. }
  61. };
  62. //减法计算器类
  63. class SubCalculator : public AbstractCalculator
  64. {
  65. public:
  66. int getResult()
  67. {
  68. return m_Num1 - m_Num2;
  69. }
  70. };
  71. //乘法计算器类
  72. class MulCalculator : public AbstractCalculator
  73. {
  74. public:
  75. int getResult()
  76. {
  77. return m_Num1 * m_Num2;
  78. }
  79. };
  80. void test01() //未使用多态的实现方法
  81. {
  82. Calculator c;
  83. c.m_Num1 = 10;
  84. c.m_Num2 = 10;
  85. cout << c.m_Num1<<"+" << c.m_Num2 << "=" << c.getResult("+") << endl;
  86. cout << c.m_Num1 << "-" << c.m_Num2 << "=" << c.getResult("-") << endl;
  87. cout << c.m_Num1 << "*" << c.m_Num2 << "=" << c.getResult("*") << endl;
  88. }
  89. void test02() //使用多态实现
  90. {
  91. //多态使用条件
  92. //父类指针或者引用指向子类对象
  93. //加法运算
  94. AbstractCalculator* abc = new AddCalculator;
  95. abc->m_Num1 = 10;
  96. abc->m_Num2 = 10;
  97. cout << abc->m_Num1 << "+" << abc->m_Num2 << "=" << abc->getResult() << endl;
  98. //堆区数据,使用完需要销毁
  99. delete abc;
  100. //减法运算
  101. abc = new SubCalculator;
  102. abc->m_Num1 = 100;
  103. abc->m_Num2 = 100;
  104. cout << abc->m_Num1 << "-" << abc->m_Num2 << "=" << abc->getResult() << endl;
  105. //堆区数据,使用完需要销毁
  106. delete abc;
  107. //乘法运算
  108. abc = new MulCalculator;
  109. abc->m_Num1 = 100;
  110. abc->m_Num2 = 100;
  111. cout << abc->m_Num1 << "*" << abc->m_Num2 << "=" << abc->getResult() << endl;
  112. //堆区数据,使用完需要销毁
  113. delete abc;
  114. }
  115. int main()
  116. {
  117. test02();
  118. system("pause");
  119. return 0;
  120. }

总结:C++开发提倡利用多态设计程序架构,因为多态优点很多

纯虚函数与抽象类

在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容
因此可以将虚函数改为纯虚函数
纯虚函数语法:virtual 返回值类型 函数名 (参数列表)= 0 ;
当类中有了纯虚函数,这个类也称为抽象类
抽象类特点

  • 无法实例化对象
  • 子类必须重写抽象类中的纯虚函数,否则也属于抽象类 ```cpp

    include

    include

    using namespace std;

class Base { public: //纯虚函数 //类中只要有一个纯虚函数就称为抽象类 //抽象类无法实例化对象 //子类必须重写父类中的纯虚函数,否则也属于抽象类 virtual void func() = 0; };

class Son :public Base { public: virtual void func() { cout << “func调用” << endl; }; };

void test01() { Base * base = NULL; //base = new Base; // 错误,抽象类无法实例化对象 base = new Son; base->func(); delete base;//记得销毁 }

int main() {

  1. test01();
  2. system("pause");
  3. return 0;

}

  1. <a name="nKAnA"></a>
  2. #### 多态案列二:
  3. ```cpp
  4. #include<iostream>
  5. #include<string>
  6. using namespace std;
  7. //制作饮品
  8. class AbstractDrinking
  9. {
  10. public:
  11. //煮水
  12. virtual void Boil() = 0;
  13. //冲泡
  14. virtual void Brew() = 0;
  15. //倒入杯中
  16. virtual void PourInCup() = 0;
  17. //加入辅料
  18. virtual void PutSometing() = 0;
  19. //制作饮品
  20. void makeDrink()
  21. {
  22. Boil();
  23. Brew();
  24. PourInCup();
  25. PutSometing();
  26. }
  27. };
  28. class Coffee : public AbstractDrinking
  29. {
  30. public:
  31. //煮水
  32. virtual void Boil()
  33. {
  34. cout << "煮农夫山泉" << endl;
  35. };
  36. //冲泡
  37. virtual void Brew()
  38. {
  39. cout << "冲泡" << endl;
  40. };
  41. //倒入杯中
  42. virtual void PourInCup()
  43. {
  44. cout << "倒入杯中" << endl;
  45. };
  46. //加入辅料
  47. virtual void PutSometing()
  48. {
  49. cout << "放入咖啡" << endl;
  50. };
  51. };
  52. class Tea : public AbstractDrinking
  53. {
  54. public:
  55. //煮水
  56. virtual void Boil()
  57. {
  58. cout << "煮矿泉水" << endl;
  59. };
  60. //冲泡
  61. virtual void Brew()
  62. {
  63. cout << "冲泡" << endl;
  64. };
  65. //倒入杯中
  66. virtual void PourInCup()
  67. {
  68. cout << "倒入杯中" << endl;
  69. };
  70. //加入辅料
  71. virtual void PutSometing()
  72. {
  73. cout << "放入柠檬" << endl;
  74. };
  75. };
  76. void doWork(AbstractDrinking* abs)
  77. {
  78. abs->makeDrink();
  79. }
  80. void test01()
  81. {
  82. //制作咖啡
  83. doWork(new Coffee);
  84. cout << "-----------" << endl;
  85. doWork(new Tea);
  86. }
  87. int main() {
  88. test01();
  89. system("pause");
  90. return 0;
  91. }

虚析构与纯虚析构

多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码
解决方式:将父类中的析构函数改为虚析构或者**
虚析构和纯虚析构共性:

  • 可以解决父类指针释放子类对象
  • 都需要有具体的函数实现

虚析构和纯虚析构区别:

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

虚析构语法:
virtual ~类名(){}
纯虚析构语法:
virtual ~类名() = 0;
类名::~类名(){}

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. //虚析构与纯虚析构
  5. class Animal {
  6. public:
  7. Animal()
  8. {
  9. cout << "Animal 构造函数调用!" << endl;
  10. }
  11. virtual void Speak() = 0;
  12. //析构函数加上virtual关键字,变成虚析构函数
  13. //virtual ~Animal()
  14. //{
  15. // cout << "Animal虚析构函数调用!" << endl;
  16. //}
  17. virtual ~Animal() = 0; ///纯虚析构
  18. };
  19. Animal::~Animal()
  20. {
  21. cout << "Animal 纯虚析构函数调用!" << endl;
  22. }
  23. //和包含普通纯虚函数的类一样,包含了纯虚析构函数的类也是一个抽象类。不能够被实例化。
  24. class Cat : public Animal {
  25. public:
  26. Cat(string name)
  27. {
  28. cout << "Cat构造函数调用!" << endl;
  29. m_Name = new string(name);
  30. }
  31. virtual void Speak()
  32. {
  33. cout << *m_Name << "小猫在说话!" << endl;
  34. }
  35. ~Cat()
  36. {
  37. cout << "Cat析构函数调用!" << endl;
  38. if (this->m_Name != NULL) {
  39. delete m_Name;
  40. m_Name = NULL;
  41. }
  42. }
  43. public:
  44. string* m_Name;
  45. };
  46. void test01()
  47. {
  48. Animal* animal = new Cat("Tom");
  49. animal->Speak();
  50. //通过父类指针去释放,会导致子类对象可能清理不干净,造成内存泄漏
  51. //怎么解决?给基类增加一个虚析构函数
  52. //虚析构函数就是用来解决通过父类指针释放子类对象
  53. delete animal;
  54. }
  55. int main() {
  56. test01();
  57. system("pause");
  58. return 0;
  59. }

总结:
1. 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
2. 如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
3. 拥有纯虚析构函数的类也属于抽象类

案列三

电脑主要组成部件为 CPU(用于计算),显卡(用于显示),内存条(用于存储)
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商
创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作。

  1. #include<iostream>
  2. #include<string>
  3. #include<vector>
  4. using namespace std;
  5. //抽象不同的类
  6. class CPU
  7. {
  8. public:
  9. virtual void calculate() = 0;
  10. };
  11. class VideoCard
  12. {
  13. public:
  14. virtual void display() = 0;
  15. };
  16. class Memory
  17. {
  18. public:
  19. virtual void storage() = 0;
  20. };
  21. class Computer
  22. {
  23. public:
  24. Computer(CPU* cpu, VideoCard* vc, Memory* mem)
  25. {
  26. m_cpu = cpu;
  27. m_vc = vc;
  28. m_mem = mem;
  29. }
  30. //提供工作函数
  31. void work()
  32. {
  33. //让零件工作起来
  34. m_cpu->calculate();
  35. m_vc->display();
  36. m_mem->storage();
  37. }
  38. //提供析构函数 释放3各电脑零件
  39. ~Computer()
  40. {
  41. if (m_cpu != NULL)
  42. {
  43. delete m_cpu;
  44. m_cpu = NULL;
  45. }
  46. if (m_vc != NULL)
  47. {
  48. delete m_vc;
  49. m_vc = NULL;
  50. }
  51. if (m_mem != NULL)
  52. {
  53. delete m_mem;
  54. m_mem = NULL;
  55. }
  56. }
  57. private:
  58. CPU* m_cpu; //CPU的指针
  59. VideoCard* m_vc; //显卡的指针
  60. Memory* m_mem; //内存的指针
  61. };
  62. //具体厂商
  63. //Intel厂商
  64. class IntelCPU : public CPU
  65. {
  66. public:
  67. virtual void calculate()
  68. {
  69. cout << "Intel的CPU开始计算了!" << endl;
  70. }
  71. };
  72. class IntelVideoCard : public VideoCard
  73. {
  74. public:
  75. virtual void display()
  76. {
  77. cout << "Intel的显卡开始显示了!" << endl;
  78. }
  79. };
  80. class IntelMemory : public Memory
  81. {
  82. public:
  83. virtual void storage()
  84. {
  85. cout << "Intel的内存开始存储了!" << endl;
  86. }
  87. };
  88. //Lenovo厂商
  89. class LenovoCPU : public CPU
  90. {
  91. public:
  92. virtual void calculate()
  93. {
  94. cout << "ILenovo的CPU开始计算了!" << endl;
  95. }
  96. };
  97. class LenovoVideoCard : public VideoCard
  98. {
  99. public:
  100. virtual void display()
  101. {
  102. cout << "Lenovo的显卡开始显示了!" << endl;
  103. }
  104. };
  105. class LenovoMemory : public Memory
  106. {
  107. public:
  108. virtual void storage()
  109. {
  110. cout << "Lenovo的内存开始存储了!" << endl;
  111. }
  112. };
  113. void test01()
  114. {
  115. //第一台电脑零件
  116. CPU* intelcpu = new IntelCPU;
  117. VideoCard* intelCard = new IntelVideoCard;
  118. Memory* intelMem = new IntelMemory;
  119. //创建第一台电脑
  120. Computer* computer1 = new Computer(intelcpu, intelCard, intelMem);
  121. computer1->work();
  122. delete computer1;
  123. cout << "-------------------------------" << endl;
  124. cout << "第二台电脑开始工作" << endl;
  125. //创建第二台电脑
  126. Computer* computer2 = new Computer(new LenovoCPU, new LenovoVideoCard,new LenovoMemory);
  127. computer2->work();
  128. delete computer2;
  129. cout << "-------------------------------" << endl;
  130. cout << "第三台电脑开始工作" << endl;
  131. //创建第三台电脑
  132. Computer* computer3 = new Computer(new LenovoCPU, new IntelVideoCard, new LenovoMemory);
  133. computer3->work();
  134. delete computer3;
  135. }
  136. int main()
  137. {
  138. test01();
  139. system("pause");
  140. return 0;
  141. }

文件操作

文本文件

写文件

写文件步骤如下:

  1. 包含头文件
    #include
  2. 创建流对象
    ofstream ofs;
  3. 打开文件
    ofs.open(“文件路径”,打开方式);
  4. 写数据
    ofs << “写入的数据”;
  5. 关闭文件
    ofs.close();

文件打开方式:

打开方式 解释
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在先删除,再创建
ios::binary 二进制方式

注意: 文件打开方式可以配合使用,利用|操作符
例如:用二进制方式写文件 **ios::binary | ios:: out**
示例:

  1. #include<iostream>
  2. #include <fstream>
  3. using namespace std;
  4. void test01()
  5. {
  6. //1、包含头文件 fstream
  7. //2、创建流对象
  8. ofstream ofs;
  9. //3、指定打开方式
  10. ofs.open("test.txt", ios::out);
  11. //4、写文件
  12. ofs << "姓名:张三" << endl;
  13. ofs << "性别:男" << endl;
  14. ofs << "年龄:18" << endl;
  15. //5、关闭文件
  16. ofs.close();
  17. }
  18. int main() {
  19. test01();
  20. system("pause");
  21. return 0;
  22. }

总结:

  • 文件操作必须包含头文件 fstream
  • 读文件可以利用 ofstream ,或者fstream类
  • 打开文件时候需要指定操作文件的路径,以及打开方式
  • 利用<<可以向文件中写数据
  • 操作完毕,要关闭文件

    读文件

    读文件与写文件步骤相似,但是读取方式相对于比较多
    读文件步骤如下:
  1. 包含头文件
    #include
  2. 创建流对象
    ifstream ifs;
  3. 打开文件并判断文件是否打开成功
    ifs.open(“文件路径”,打开方式);
  4. 读数据
    四种方式读取
  5. 关闭文件
    ifs.close();

示例:

  1. #include <fstream>
  2. #include <string>
  3. void test01()
  4. {
  5. //1、包含头文件
  6. //2、创建流对象
  7. ifstream ifs;
  8. //3、打开文件,并且判断是否打开成功
  9. ifs.open("test.txt", ios::in);
  10. //4、判断是否打开成功
  11. if (!ifs.is_open())
  12. {
  13. cout << "文件打开失败" << endl;
  14. return;
  15. }
  16. //5、读文件
  17. //第一种方式
  18. //char buf[1024] = { 0 };
  19. //while (ifs >> buf)
  20. //{
  21. // cout << buf << endl;
  22. //}
  23. //第二种
  24. //char buf[1024] = { 0 };
  25. //while (ifs.getline(buf,sizeof(buf)))
  26. //{
  27. // cout << buf << endl;
  28. //}
  29. //第三种
  30. string buf;
  31. while (getline(ifs, buf))
  32. {
  33. cout << buf << endl;
  34. }
  35. //第四种(不推荐)
  36. //char c;
  37. //while ((c = ifs.get()) != EOF)
  38. //{
  39. // cout << c;
  40. //}
  41. //6、关闭文件
  42. ifs.close();
  43. }
  44. int main() {
  45. test01();
  46. system("pause");
  47. return 0;
  48. }

总结:

  • 读文件可以利用 ifstream ,或者fstream类
  • 利用is_open函数可以判断文件是否打开成功
  • close 关闭文件

    二进制文件(?)

    写文件

    二进制方式写文件主要利用流对象调用成员函数write
    函数原型 :ostream& write(const char * buffer,int len);
    参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
    示例: ```c

    include

    include

    include

    using namespace std;

class Person { public: char m_Name[64]; int m_Age; };

//二进制文件 写文件 void test01() { //1、包含头文件

  1. //2、创建输出流对象
  2. ofstream ofs("person.txt", ios::out | ios::binary);
  3. //3、打开文件
  4. //ofs.open("person.txt", ios::out | ios::binary);
  5. Person p = { "张三" , 18 };
  6. //4、写文件
  7. ofs.write((const char*)&p, sizeof(p));
  8. //5、关闭文件
  9. ofs.close();

}

int main() {

  1. test01();
  2. system("pause");
  3. return 0;

}

  1. 总结:
  2. - 文件输出流对象 可以通过write函数,以二进制方式写数据
  3. <a name="G27si"></a>
  4. #### 读文件
  5. 二进制方式读文件主要利用流对象调用成员函数read<br />函数原型:`istream& read(char *buffer,int len);`<br />参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数<br />示例:
  6. ```c
  7. #include<iostream>
  8. #include <fstream>
  9. #include <string>
  10. using namespace std;
  11. class Person
  12. {
  13. public:
  14. char m_Name[64];
  15. int m_Age;
  16. };
  17. //二进制文件 读文件
  18. void test01()
  19. {
  20. //1、包含头文件
  21. //2、创建流文件
  22. ifstream ifs("person.txt", ios::in | ios::binary);
  23. //3、判断文件是否打开成功
  24. if (!ifs.is_open())
  25. {
  26. cout << "文件打开失败" << endl;
  27. }
  28. //4、读文件
  29. Person p;
  30. ifs.read((char*)&p, sizeof(p));
  31. cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
  32. //5、关闭文件
  33. ifs.close();
  34. }
  35. int main() {
  36. test01();
  37. system("pause");
  38. return 0;
  39. }
  • 文件输入流对象 可以通过read函数,以二进制方式读数据

    项目实战——职工管理系统

    管理系统需求

    创建管理类

  • 与用户交互

  • 对职工增删改查的操作
  • 与文件的读写交互

    菜单功能

    添加成员函数

退出功能

提供接口功能

创建职工类

  • 职工类
  • 经理类
  • 老板类

    添加职工

    功能描述:批量添加职工,并且保存到文件中

    文件交互-写文件(?写文件时总是报错访问冲突)

    添加一个文件,保存职工信息

    文件交互-读文件

  • 文件不存在

  • 文件存在,但为空

在workerManager.cpp中的构造函数追加代码:

  1. //文件存在,并且没有记录
  2. char ch;
  3. ifs >> ch;
  4. if (ifs.eof())
  5. {
  6. cout << "文件为空!" << endl;
  7. this->m_EmpNum = 0;
  8. this->m_FileIsEmpty = true;
  9. this->m_EmpArray = NULL;
  10. ifs.close();
  11. return;
  12. }

追加代码位置如图:
将文件创建后清空文件内容,并测试该情况下初始化功能
我们发现文件不存在或者为空清空 m_FileIsEmpty 判断文件是否为空的标志都为真,那何时为假?
成功添加职工后,应该更改文件不为空的标志
void WorkerManager::Add_Emp()成员函数中添加:

  1. //更新职工不为空标志
  2. this->m_FileIsEmpty = false;
  • 文件存在且保存职工数据

在workerManager.h中添加成员函数 int get_EmpNum();

  1. //统计人数
  2. int get_EmpNum();

workerManager.cpp中实现

  1. int WorkerManager::get_EmpNum()
  2. {
  3. ifstream ifs;
  4. ifs.open(FILENAME, ios::in);
  5. int id;
  6. string name;
  7. int dId;
  8. int num = 0;
  9. while (ifs >> id && ifs >> name && ifs >> dId)
  10. {
  11. //记录人数
  12. num++;
  13. }
  14. ifs.close();
  15. return num;
  16. }

在workerManager.cpp构造函数中继续追加代码:

  1. int num = this->get_EmpNum();
  2. cout << "职工个数为:" << num << endl; //测试代码
  3. this->m_EmpNum = num; //更新成员属性

手动添加一些职工数据,测试获取职工数量函数
初始化数组
根据职工的数据以及职工数据,初始化workerManager中的Worker ** m_EmpArray 指针
在WorkerManager.h中添加成员函数 void init_Emp();

  1. //初始化员工
  2. void init_Emp();

在WorkerManager.cpp中实现

  1. void WorkerManager::init_Emp()
  2. {
  3. ifstream ifs;
  4. ifs.open(FILENAME, ios::in);
  5. int id;
  6. string name;
  7. int dId;
  8. int index = 0;
  9. while (ifs >> id && ifs >> name && ifs >> dId)
  10. {
  11. Worker * worker = NULL;
  12. //根据不同的部门Id创建不同对象
  13. if (dId == 1) // 1普通员工
  14. {
  15. worker = new Employee(id, name, dId);
  16. }
  17. else if (dId == 2) //2经理
  18. {
  19. worker = new Manager(id, name, dId);
  20. }
  21. else //总裁
  22. {
  23. worker = new Boss(id, name, dId);
  24. }
  25. //存放在数组中
  26. this->m_EmpArray[index] = worker;
  27. index++;
  28. }
  29. }

在workerManager.cpp构造函数中追加代码

  1. //根据职工数创建数组
  2. this->m_EmpArray = new Worker *[this->m_EmpNum];
  3. //初始化职工
  4. init_Emp();
  5. //测试代码
  6. for (int i = 0; i < m_EmpNum; i++)
  7. {
  8. cout << "职工号: " << this->m_EmpArray[i]->m_Id
  9. << " 职工姓名: " << this->m_EmpArray[i]->m_Name
  10. << " 部门编号: " << this->m_EmpArray[i]->m_DeptId << endl;
  11. }

运行程序,测试从文件中获取的数据
至此初始化数据功能完毕,测试代码可以注释或删除掉!

显示职工

完成显示职工和删除职工视频学习,还未动手操作

模板

模板概念

函数模板

函数模板语法

函数模板注意事项

普通函数与函数的

类模板

类模板语法

STL(标准模板库)初识

STL基本概念

  • STL(Standard Template Library,标准模板库)
  • STL 从广义上分为: 容器(container) 算法(algorithm) 迭代器(iterator)
  • 容器算法之间通过迭代器进行无缝连接。
  • STL 几乎所有的代码都采用了模板类或者模板函数

    STL六大组件

    STL大体分为六大组件,分别是:容器、算法、迭代器、仿函数、适配器(配接器)、空间配置器
  1. 容器:各种数据结构,如vector、list、deque、set、map等,用来存放数据。
  2. 算法:各种常用的算法,如sort、find、copy、for_each等
  3. 迭代器:扮演了容器与算法之间的胶合剂。
  4. 仿函数:行为类似函数,可作为算法的某种策略。
  5. 适配器:一种用来修饰容器或者仿函数或迭代器接口的东西。
  6. 空间配置器:负责空间的配置与管理