C++从入门到入土(入土第15天)

1. C++初识别

1.1 变量

#include<iostream>
using namespace std;

int main2()
{
	//变量创建的语法:数据类型 变量名 = 变量初始值
	int a = 10;
	cout << "a=" << a << endl;
	system("pause");
	return 0;
}

1.2 常量

#include<iostream>
using namespace std;
//常量的定义方式
	/*
	1.#define 宏常量
	2.const修饰的变量
	*/

#define Day 7
int main3()
{
	const int month = 12;
	cout << "一周有:" << Day << "天";
	cout << "一月有:" << month << "月";
	system("pause");
	return 0;
}

2. 数据类型

2.1 整型

#include<iostream>
using namespace std;

int main4()
{
	//整型
	//1、短整型
	short num1 = 10;
	//2、整型
	int num2 = 10;
	//3、长整型
	long num3 = 10;
	//4、长长整型
	long long num4 = 10;
	cout << "num1 = " << num1 << endl;
	cout << "num2 = " << num2 << endl;
	cout << "num3 = " << num3 << endl;
	cout << "num4 = " << num4 << endl;
	system("pause");
	return 0;
}

2.2 sizeof关键字

#include<iostream>
using namespace std;
//sizeof 关键字可以统计数据类型所占内存大小
int main5()
{
	//1、短整型
	short num1 = 10;
	//2、整型
	int num2 = 10;
	//3、长整型
	long num3 = 10;
	//4、长长整型
	long long num4 = 10;
	cout << "short所占内存空间未:" << sizeof(short) << endl;
	cout << "int所占内存空间未:" << sizeof(int) << endl;
	cout << "long所占内存空间未:" << sizeof(long) << endl;
	cout << "long long所占内存空间未:" << sizeof(long long) << endl;
	system("pause");
	return 0;
}

2.3 实型

**作用:**用来表示小数

浮点型变量分为两种

  • 单精度float
  • 双精度double

两者的区别在于表示的有效数字范范围不同

数据类型占用空间有效数字范围
float4字节7位有效数字
double8字节15—16位有效数字
#include<iostream>
using namespace std;
//默认情况下,输出一个小数,会显示6位有效数字
int main()
{
	//1、单精度
	float f1 = 3.14f;
	cout << "f1=" << f1 << endl;

	//2、双精度
	double f2 = 3.14;
	cout << "f2=" << f2 << endl;

	//统计float和double占用内存空间大小
	cout << "float占用内存空间大小:" << sizeof(f1) << endl;
	cout << "double占用内存空间大小:" << sizeof(f2) << endl;

	//科学计数法
	float f3 = 3e2;		//3*10^2
	cout << f3 << endl;
	
	
	float f4 = 3e-2;	//3*0.1^2
	cout << f4 << endl;

	system("pause");
	return 0;
}

2.4 字符型

**作用:**字符型变量用于显示单个字符

语法:

char ch = 'a';

注意:

  • 在显示字符串变量时,用单引号将字符括起来
  • 单引号内只能有一个字符,不能是字符串

C++中字符型变量只占用1个字节

字符型变量并不是把字符本身放到内存中存储起来,而是将对应的ASCII编码放入存储单元中

#include<iostream>
using namespace std;

int main()
{
	//1、字符型变量创建方式
	char ch = 'a';
	cout << ch << endl;

	//2、字符型变量所占内存空间大小
	cout << sizeof(char) << endl;

	//3、字符型变量常见错误
	/*
	创建字符型变量,要用单引号
	创建字符型变量,单引号中只能有一个字符
	*/

	//4、字符型变量对应ASCII编码
	/*
	a:97
	A:65
	*/
	cout << (int)ch << endl;	//97
	

	system("pause");
	return 0;
}

2.5 转义字符

**作用:**用于表示一些不能显示出来的ASCII字符

现阶段常用的转义字符

\n,\\,\t
转义字符含义ASCII码值
\a警报007
\b退格(BS),将当前位置移到前一列008
\f换页(FF),将当前位置移到下页开头012
\n换行(LF),将当前位置移到下一行开头010
\r回车(CR),将当前位置移到本行开头013
\t水平制表(HT),跳到下一个tab位置009
\v垂直制表(VT)011
\代表一个反斜杠字符092
代表一个单引号字符039
‘’代表一个双引号字符034
?代表一个问好063
\0数字0000
\ddd8进制转义字符,d范围0-73位八进制
\xhh16进制转义字符3位十六进制
#include<iostream>
using namespace std;

int main()
{
	//转义字符
	//换行符 \n
	cout << "hello world\n";

	//反斜杠 \\

	cout << "\\" << endl;

	//水平制表符	\t
	//作用可以整齐的输出数据
	cout << "aaa\tbbb" << endl;

	system("pause");
	return 0;
}

2.6 字符串型

**作用:**用于表示一串字符

两种风格:

  • C字符串

    char 变量名[] = "字符串值"
    
  • C++字符串

    string 变量名 = "字符串值"
    
#include<iostream>
#include<string>	//用C++风格字符串时,要包含这个头文件
using namespace std;

int main()
{
	//C类型字符串
	char str[] = "nibukun";
	cout << str << endl;

	//C++类型字符串
	string str2 = "wokun";
	cout << str2 << endl;

	system("pause");
	return 0;
}

2.7 布尔类型

**作用:**布尔数据类型表示真或者假的值

bool类型只有两个值

  • true
  • false

bool类型占1个字节大小

#include<iostream>
using namespace std;

int main()
{
	//1、创建bool数据类型
	bool flag = true;	
	cout << flag << endl;	//1

	flag = false;
	cout << flag << endl;	//0

	//2、查看bool数据类型作占内存空间
	cout << sizeof(bool) << endl;	//1	
	system("pause");
	return 0;
}

2.8 数据的输入

**作用:**用于从键盘获取数据

**关键字:**cin

语法:

cin>>变量;
#include<iostream>
#include<string>
using namespace std;

int main11() {

	//1、整型
	int a = 0;
	cout << "请给整型变量赋值:" << endl;
	cin >> a;
	cout << "a=" << a << endl;

	//2、浮点型
	float f = 0;
	cout << "请给浮点型变量赋值:" << endl;
	cin >> f;
	cout << "f=" << f << endl;

	//3、字符型
	char c = 0;
	cout << "请给字符型变量赋值:" << endl;
	cin >> c;
	cout << "c=" << c << endl;

	//4、字符串型
	string str = "";
	cout << "请给字符串型变量赋值:" << endl;
	cin >> str;
	cout << "str=" << str << endl;

	//5、布尔类型
	bool flag = true;
	cout << "请给布尔类型变量赋值:" << endl;
	cin >> flag;
	cout << "flag=" << flag << endl;

	system("pause");
	return 0;
}

3. 运算符

**作用:**用于执行代码的运算

运算符类型作用
算术运算符用于处理四则运算
赋值运算符用于将表达式的值赋值给变量
比较运算符用于表达式的比较,并返回一个真值和一个假值
逻辑运算符用于根据表达式的值返回真值或者假值

3.1 算数运算符

**作用:**用于处理四则运算

运算符术语
+正号、加
-负号、减
*
/
%取余
++自增
自减
#include<iostream>
using namespace std;

int main()
{
	//加减乘除
	int a1 = 10;
	int b1 = 3;
	cout << a1 + b1 << endl;
	cout << a1 - b1 << endl;
	cout << a1 * b1 << endl;
	//除数不能为0
	cout << a1 / b1 << endl;		//两个整数相除结果依然是整数,会去除小数部分

	double d1 = 0.5;
	double d2 = 0.25;
	cout << d1 / d2 << endl;
	
	//%本质就是求余数
	int a1 = 10;
	int b1 = 3;
	cout << a1 % b1;

	//1、前置递增
	int a = 10;
	++a;
	cout << a << endl;

	//2、后置递增
	int b = 10;
	b++;
	cout << b << endl;

	//2、两者区别
	/*
	前置递增:先让变量+1然后进行表达式运算
	后置递增:先进行表达式运算后让变量加一
	*/

	system("pause");
	return 0;
}

3.2 赋值运算符

**作用:**用于将表达式的值赋给变量

赋值运算符包括以下几个符号

运算符术语
=赋值
+=加等于
-=减等于
*=乘等于
/=除等于
%=模等于

3.3 比较运算符

**作用:**用于表达式的比较,并返回一个真值或假值

运算符术语
==等于
!=不等于
>小于
<大于
>=大于等于
<=小于等于

3.4 逻辑运算符

**作用:**用于根据表达式的值返回真值或者假值

表达式术语
!
&&
||

与(&&)

//逻辑运算符 与&&
	//同真为真,同假为假
	int a = 10;
	int b = 10;
	cout << (a&&b) << endl;	//1

	a = 0;
	cout << (a&&b) << endl;	//0
	system("pause");
	return 0;

或(||)

//同假为假,其余为真
int a = 10;
	int b = 10;
	cout << (a || b) << endl;	//1


	b = 0;
	cout << (a || b) << endl;	//1

	a = 0;
	cout << (a || b) << endl;	//0

4. 程序流程结构

C/C++支持的最基本的三种程序运行结构:顺序结构,选择结构,循环结构

  • 顺序结构:程序按照顺序执行,不发生跳转
  • 选择结构:依据条件是否满足,有选择的执行相应的功能
  • 循环结构:一句条件是否满足,循环多次执行某段代码

4.1 选择结构

1. if语句

**作用:**执行满足条件的语句

if语句的三种形式

  • 单行格式if语句语法格式:

    if(条件)
    {
    条件满足执行的语句;
    }

    //选择结构 单行if语句
    	//让用户输入分数,如果分数大于600,视为考上
    	int score = 0;
    	cout << "请输入一个分数:" << endl;
    	cin >> score;
    	if (score > 600)
    	{
    		cout << "考上" << endl;
    	}
    
  • 多行格式if语句格式:

    if(条件)
    {
    条件满足执行的语句;
    }else

    {

    ​ 条件满足执行的语句;

    }

    //选择结构 多行if语句
    	//分数大于600,打印考上,否则打印未考上
    	int score = 0;
    	cout << "请输入分数:";
    	cin >> score;
    	if (score > 600)
    		cout << "考上!"<<endl;
    	else
    		cout << "没考上。"<<endl;
    
  • 多行格式if语句

    if(条件1)
    {
    条件满足执行的语句;
    }else if(条件2)

    {

    ​ 条件满足执行的语句;

    }

    else{都不满足执行}

//选择结构,多条件if语句
	/*
	1、输入分数,大于600,考一本
	2、大于500,考二本
	3、大于400,考三本
	否则视为未考上
	*/
	int score = 0;
	cout << "请输入你的分数:" << endl;
	cin >> score;
	if (score > 600)
		cout << "考一本!" << endl;
	else if (score > 500)
		cout << "考二本!" << endl;
	else if (score > 400)
		cout << "考三本!" << endl;
	else
		cout << "未考上。" << endl;
  • 嵌套if语句:在if语句中,可以使用嵌套if语句
//嵌套if语句
	/*
	提示用户输入一个分数;如果>600视为考上一本,>500视为考上二本,>400视为考上三本
	其余视为未考上。
	在一本分数中,大于700,考入北大,大于650,考入清华,大于600人大
	*/

	int score = 0;
	cout << "请输入您的分数:" << endl;
	cin >> score;
	if (score > 600)
	{
		if (score > 700)
			cout << "考入北大!" << endl;
		else if (score > 650)
			cout << "考入清华!" << endl;
		else
			cout << "考入人大" << endl;
	}
	else if (score > 500)
		cout << "考二本" << endl;
	else if (score > 400)
		cout << "考三本" << endl;
	else
		cout << "未考上。" << endl;

三只小猪

#include<iostream>
using namespace std;
/*
	键入三只小猪的体重,比较谁最重
*/
int main()
{
	int num1 = 0;
	int num2 = 0;
	int num3 = 0;
	cout << "输入三只小猪的重量" << endl;
	cin >> num1;
	cin >> num2;
	cin >> num3;
	cout << "小猪A的体重是:" << num1 << endl;
	cout << "小猪B的体重是:" << num2 << endl;
	cout << "小猪C的体重是:" << num3 << endl;
	if (num1 > num2)
	{
		if (num1 > num3)
			cout << "小猪A最重" << endl;
		else
			cout << "小猪C最重" << endl;
	}
	else
	{
		if (num2 > num3)
			cout << "小猪B最重" << endl;
		else
			cout << "小猪C最重" << endl;
	}


	system("pause");
	return 0;
}

2. 三目运算符

**作用:**通过三目运算符实现简单的判断

**语法:**表达式1?表达式2:表达式3

解释:

如果表达式1的值为真,则执行表达式2,并返回表达式2的结果

否则,则执行表达式3,并返回表达式3的结果

//三目运算符
	/*
	创建三个变量 a b c
	将a和b作比较,将变量大的值赋值给变量c
	*/
	int a = 10;
	int b = 20;
	int c = 0;
	c = (a > b ? a : b);
	cout << "c=" << c << endl;

	//在C++中,三目运算符返回的是变量,可以继续赋值
	(a > b ? a : b) = 100;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;	//b=100

3. switch语句

**作用:**执行多条件分支语句

语法:

switch(表达式)
{
    case 结果1:
        执行语句;
        break;
       ...
    case 结果2:
        执行语句;
        break;
    default:
        执行语句;
        break;
}
//switch
	/*
	给电影评分
	10—9 经典
	8-7   非常好
	6-5   一般
	5以下 烂片
	*/

	int score = 0;
	cout << "请给电影打分:" << endl;
	cin >> score;
	switch (score)
	{
	case 10:
		cout << "经典电影" << endl;
		break;
	case 9:
		cout << "经典电影" << endl;
		break;
	case 8:
		cout << "非常好" << endl;
		break;
	case 7:
		cout << "非常好" << endl;
		break;
	case 6:
		cout << "一般" << endl;
		break;
	case 5:
		cout << "一般" << endl;
		break;
	default:
		cout << "烂片。" << endl;
		break;
	}
switch缺点:判断时候只能是整型或者字符型,不可以是一般区间
优点:结构清晰,执行效率高

4.2 循环结构

1. while循环语句

**作用:**满足循环条件,执行循环语句

语法:

while(循环条件)
{
	循环语句
}

**解释:**只要循环条件的结果为真,就执行循环语句

//while 循环
	//打印0-9十个数字
	int i = 0;
	while (i < 10)
	{
		cout << i++ << endl;
	}

猜数字

//while循环案例:猜数字
	/*
	随机生成1-100之间的数字,进行猜测,如果猜错提示过大或者过小,否则恭喜玩家胜利,退出游戏
	*/
	
	//添加随机数种子,作用利用当前系统时间生成随机数,防止每次随机数都是一样
	srand((unsigned int)time(NULL));
	int num = rand() % 100 + 1;  //rand() % 100 生成0-99之间的随机数
	int val = 0;
	cout << "请输入猜测的数字!" << endl;
	cin >> val;
	while (num != val)
	{	
		//猜错:提示游戏结果
		if (num > val)
		{
			cout << "猜测数字过小请重新输入!" << endl;
			cin >> val;
		}
		else if (num < val)
		{
			cout << "猜测数字过大请重新输入!" << endl;
			cin >> val;
		}
		else
		{
			cout << "恭喜猜测成功!" << endl;
			//猜对:退出游戏
			break;
		}
	}

2. do while循环语句

**作用:**满足条件时,执行循环语句

语法:

do
{
    循环语句;
}while(循环条件);

**注意:**与while区别在于do while会先执行一次循环语句,再判断循环条件

求三位水仙花数:

/*
	水仙花数是指一个三位数,它的每个位上的数字的3次幂之和等于它本身
	求出所有三位数中的水仙花数
*/
	int num = 0;
	do
	{
		int a = 0;
		int b = 0;
		int c = 0;
		//个位
		a = num % 10;
		//十位
		b = num / 10 % 10;
		//百位
		c = num / 100;
		if (num == a*a*a + b*b*b + c*c*c)
			cout << num << endl;
		num++;
	} while (num < 1000);

3. for循环语句

作用:满足循环条件,执行循环语句

语法

for(起始表达式;条件表达式:末尾循环体)
{
    循环语句;
}

示例代码

/*打印数字0-9*/
int i = 0;
for (i = 0; i < 10; i++)
{
	cout << i << endl;
}

练习案例

//敲桌子
	/*
	从1开始数到100,如果数字个位含有7或者十位含有7,或者是7的倍数,就打印敲桌子
	否则直接打印输出
	*/
	for (int i = 1; i < 101; i++)
	{
		if (i % 10 == 7 || int(i / 10) == 7 || i % 7 == 0)
			cout << "敲桌子" << endl;
		else
			cout << i << endl;
	}

4. 嵌套循环

作用:在循环体中再嵌套一层循环

案例

//嵌套循环案例
/*打印九九乘法表*/
for (int i = 1; i < 10; i++)
{
	for (int j = 1; j <= i; j++)
		cout << j << "*" << i << "=" << i * j << "\t";
	cout << endl;
}

4.3 跳转语句

1、break

作用:用于跳出选择结构或者循环结构

使用时机

  • 出现switch条件语句中,作用是终止case并跳出switch
  • 出现再循环语句中,作用是跳出当前的循环语句
  • 出现再嵌套循环中,跳出最近的内存循环语句

2、continue

作用:在循环语句中,跳过本次循环中余下尚未执行的语句,继续执行下一次循环

3、goto语句

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

语法

goto 标记;

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

示例

	cout << "1、xxxx" << endl;
	cout << "2、xxxx" << endl;

	goto FLAG;
	cout << "3、xxxx" << endl;
	cout << "4、xxxx" << endl;
	FLAG:
	cout << "5、xxxx" << endl;

一般不推荐使用goto语句

5. 数组

5.1 概述

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

  • 数组中的每个数据元素都是相同的数据类型
  • 数组是由连续的内存位置组成的

5.2 一维数组

一维数组定义的三种方式

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

示例

int main()
{
	//定义数组
	int arr[5];
	arr[0] = 1;
	arr[1] = 2;
	arr[2] = 3;
	arr[3] = 4;
	arr[4] = 5;

	int arr2[5] = { 1, 2, 3, 4, 5 };

	int arr3[] = { 1, 2, 3, 4, 5 };

	system("pause");
	return 0;
}

一维数组名称的用途

  • 可以统计整个数组在内存中的长度
  • 可以获取数组在内存中的首地址

示例

//数组名用途
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
cout << "整个数组占用内存空间为:" << sizeof(arr) << endl;	//40
cout << "每个元素所占用的内存空间为:" << sizeof(arr[0]) << endl;
cout << "数组中元素个数为:" << sizeof(arr) / sizeof(arr[0]) << endl;

cout << "数组的首地址为:" << arr << endl;
cout << "数组的第一个元素地址为:" << &arr[0] << endl;
//数组名是常量,不可以进行赋值操作

案例:五只小猪称体重

//在一个数组中记录了五只小猪的体重,找出并打印最重的小猪的体重
	int arr[5] = { 300,350,200,400,250 };
	int max = 0;
	for (int i = 0; i < 5; i++)
	{
		if (max < arr[i])
			max = arr[i];
	}
	cout << "最重的小猪的体重是:" << max << endl;

案例:逆置

int arr[5] = { 1,3,2,5,4 };
int j=sizeof(arr)/sizeof(arr[0])-1;	//末尾下标
for (int i = 0, j; i < j; i++, j--)
{
	int temp = arr[i];
	arr[i] = arr[j];
	arr[j] = temp;
}
for (int i = 0; i < 5; i++)
	cout << arr[i] << endl;

案例:冒泡排序

作用:最常见的排序算法,对数组内元素进行排序

1、比较相邻的元素,如果第一个比第二个大,就交换他们两个

2、对每一对相元素做相同工作,执行完毕后,找出第一个最大值

3、重复以上步骤,每次比较次数-1,直到不需要比较

示例

//冒泡排序,实现升序
	int arr[9] = { 4,2,8,0,5,7,1,3,9 };
	cout << "排序前的结果:";
	for (int i = 0; i < 9; i++)
		cout << arr[i] << "   ";
	cout << endl;

	//总共排序轮数为 元素个数 -1
	for (int i = 0; i < 9 - 1; i++)
	{
		//内层循环对比 次数=元素个数-当前轮数-1
		for (int j = 0; j < 9 - i - 1; j++)
		{
			//如果第一个元素比第二个元素大,进行交换
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	cout << "排序后的结果:";
	for (int i = 0; i < 9; i++)
		cout << arr[i] << "   ";
	cout << endl;

5.3 二维数组

//二维数组的定义方式
	/*
	1、数据类型 数组名[行数][列数];
	2、数据类型 数组名[行数][列数]={{数据1,数据2},{数据1,数据2}...};
	3、数据类型 数组名[行数][列数]={数据1,数据2,数据3..};
	4、数据类型 数组名[ ][列数]={数据1,数据2,数据3..};
	*/

	int arr1[2][3];
	int arr2[2][3] = {
		{1,2,3},
		{4,5,6}
	};

	int arr3[2][3] = { 1,2,3,4,5,6 };

	int arr4[][3] = { 1,2,3,4,5,6 };

二维数组数组名

  • 查看二维数组所占内存空间
  • 获取二维数组首地址

示例:

//1、查看占用内存空间大小
	int arr[2][3] =
	{
		{1,2,3},
		{4,5,6}
	};
	cout << "二维数组所占内存空间为:" << sizeof(arr) << endl;	//24
	cout << "二维数组第一行所占内存空间为:" << sizeof(arr[0]) << endl;	//12
	cout << "二维数组一个元素所占内存空间为:" << sizeof(arr[0][0]) << endl;	//4

	//2、可以查看二维数组的首地址
	cout << "二维数组首地址是:" << arr << endl;
	cout << "二维数组第一行首地址是:" << arr[0] << endl;
	cout << "二维数组第一个元素地址是:" << &arr[0][0] << endl;

二维数组应用案例-考试成绩统计

//1、创建二维数组
	int score[3][3] =
	{
		{100,100,100},
		{90,50,100},
		{60,70,80},
	};
	//2、统计每个人的总和分数
	cout << "分数为:" << endl;
	for (int i = 0; i < 3; i++)
	{
		int sum = 0;	//统计分数综合
		for (int j = 0; j < 3; j++)
		{
			sum += score[i][j];
		}
		cout << names[i]<< "个人的成绩是:" << sum << endl;
	}

6. 函数

6.1 概述

作用:将一段经常使用的代码封装起来,减少重复代码。

一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能

6.2 函数的定义

函数的定义一般有5个步骤

1、返回值类型

2、函数名

3、参数列表

4、函数体语句

5、return表达式

语法

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

示例

//加法函数,实现两个整型相加,并且将相加的结果进行返回
int add(int num1, int num2)
{
	return num1 + num2;
}

6.3 函数的调用

功能:使用定义好的函数

语法

函数名(参数)

示例

//加法函数,实现两个整型相加,并且将相加的结果进行返回
//num1和num2,形参
int add(int num1, int num2)
{
	return num1 + num2;
}
int main()
{
	int a = 1;
	int b = 2;
	//函数调用
	/*
	a,b:实参
	当调用函数的时候,实参的值会传递给形参
	*/
	int c = add(a, b);
	cout << "c=" << c << endl;

	system("pause");
	return 0;
}

6.4 值传递

  • 所谓值传递,就是函数调用时,实参将数值传递给形参
  • 值传递时,如果形参发生变化,不会影响实参

示例

//值传递
//定义函数,实现两个数字进行交换的函数
void swap(int num1, int num2)
{
	cout << "交换前:" << endl;
	cout << "num1=" << num1 << endl;
	cout << "num2=" << num2 << endl;

	int temp = num1;
	num1 = num2;
	num2 = temp;

	cout << "交换后:" << endl;
	cout << "num1=" << num1 << endl;
	cout << "num2=" << num2 << endl;
	//返回值不需要的时候,可以不写return
}

int main()
{
	int a = 10;
	int b = 20;

	cout << "a=" << a << endl;	//10
	cout << "b=" << b << endl;	//20

	//当我们做值传递的时候,函数的形参发生变化,并不会影响到实参
	//函数调用
	swap(a, b);

	cout << "a=" << a << endl;	//10
	cout << "b=" << b << endl;	//20

	system("pause");
	return 0;
}

值传递时,形参修饰不了实参

6.5 函数的常见样式

常见的函数样式有:

无参无返

有参无返

无参有返

有参有返

示例

//函数常见样式
//1、无参无返
void test01()
{
	cout << "this is test01" << endl;
}

//2、有参无返
void test02(int a)
{
	cout << "this is test02" << endl;
}

//3、无参有返
int test03()
{
	cout << "this is test03" << endl;
	return 1;
}

//4、有参有返
int test04(int a)
{
	cout << "this is test04" << endl;
	return 1;
}

int main()
{
	//无参无返函数调用
	test01();	//this is test01

	//有参无返函数调用
	test02(100);	//this is test02

	//无参有返函数调用
	int num1 = test03();
	cout << "num1=" << num1 << endl;	//num1=1

	//有参有返函数调用
	int num2 = test04(100);
	cout << "num2=" << num2 << endl;

	system("pause");
	return 0;
}

6.6 函数的声明

作用:告诉编译器函数名称和如何调用函数。函数的实际主体可以单独定义

函数的声明可以多次,函数的定义只能有一次

示例

//提前告诉编译器函数的存在
//声明可以写多次,定义只能写一次
int max(int a, int b);
int main54()
{
	int a = 10;
	int b = 20;
	cout << max(a, b) << endl;

	system("pause");
	return 0;
}

//比较函数,实现两个整型数字进行比较,返回较大的值
int max(int a, int b)
{
	return a > b ? a : b;
}

6.7 函数的分文件编写

作用:让代码结构更清晰

函数分文件编写一般有四个步骤

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

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

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

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

示例

swap.h

#include<iostream>
using namespace std;
//函数声明
void swap(int a, int b);

swap.cpp

#include"swap.h"

//函数定义
void swap(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
}

main.cpp

#include"swap.h"

int main()
{
	int a = 10;
	int b = 20;
    //函数调用
	swap(a, b);

	system("pause");
	return 0;
}

7. 指针

7.1 指针的基本概念

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

  • 内存编号是从0开始编制的,一般采用十六进制数字表示
  • 可以利用指针变量保存地址

7.2 指针变量的定义和使用

指针变量定义语法:

数据类型 * 变量名;

示例

int main()
{
	int a = 10;

	//1、定义指针
	int * p;
	//让指针p指向变量a的地址
	p = &a;
	cout << "a的地址为:" << &a << endl;  //00F8FBB4
	cout << "指针p为:" << p << endl;	//00F8FBB4

	//2、使用指针
	//可以使用解引用的方式来找到指针指向的内存	*指针
	*p = 1000;
	cout << "a=" << a << endl;	//1000
	cout << "*p=" << *p << endl;//1000

	system("pause");
	return 0;
}

7.3 指针所占内存空间

示例

int main()
{
	//指针所占内存空间
	int a = 10;
	int * p = &a;
	//在32b操作系统下,指针是占4个字节空间大小的,不管什么数据类型
	//在64b操作系统下,指针是占8个字节空间大小的,不管什么数据类型
	cout << "sizeof(int *)=" << sizeof(int *) << endl;	//sizeof(int *)=4
	cout << "sizeof(float *)=" << sizeof(float *) << endl;	//4
	cout << "sizeof(double *)=" << sizeof(double *) << endl;	//4
	cout << "sizeof(char *)=" << sizeof(char *) << endl;	//4

	system("pause");
	return 0;
}

7.4 空指针和野指针

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

用途:初始化指针变量

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

示例1:空指针

int main()
{
	//空指针
	//1、空指针用于给指针变量进行初始化
	int * p = NULL;
	//2、空指针是不可以被访问的。0-255之间的内存编号是被系统占用的,因此不可以被访问

	system("pause");
	return 0;
}

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

空指针和野指针都不是我们申请的空间,因此不要访问

7.5 const修饰指针

const修饰指针有三种情况

  • const修饰指针 常量指针
  • const修饰变量 指针常量
  • const即修饰指针,又称修饰常量

示例:

int main()
{
	//1、const修饰指针——常量指针
	int a = 10;
	int b = 10;

	const int * p = &a;
	//指针指向的值不可以改,指针的指向可以改
	p = &b;		//正确

	//2、const修饰常量——指针常量
	int * const p2 = &a;
	//指针的指向不可以改,指针指向的值可以改
	*p2 = 20;	//正确

	//3、const即修饰指针也修饰常量
	//指针的指向和指针指向的值都不可以修改
	const int * const p3 = &a;

	system("pause");
	return 0;
}

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

7.6 指针和数组

作用:利用指针访问数组中元素

示例:

int main()
{
	//利用数组访问数组中的数据
	int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
	cout << "数组中第一个元素是:" << arr[0] << endl;
	//指针p指向数组首地址
	int * p = arr;

	cout << "利用指针访问第一个元素:" << *p << endl;

	p++;	//让指针向后偏移了四个字节

	cout << "利用指针访问第二个元素:" << *p << endl;

	cout << "利用指针遍历数组" << endl;

	int *p2 = arr;
	for (int i = 0; i < 10; i++)
	{
		cout << *p2 << endl;
		p2++;
	}
	system("pause");
	return 0;
}

7.7 指针和函数

作用:利用指针作函数参数,可以修改实参的值

示例:

//实现两个数字进行交换
void swap01(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << "swap01中的a=" << a << endl;	//a=20
	cout << "swap01中的b=" << b << endl;	//b=10
}

void swap02(int * p1, int * p2)
{
	int temp = *p1;
	*p1 = *p2;
	*p2 = temp;
}
int main()
{
	//1、值传递
	//值传递不会改变实参
	int a = 10;
	int b = 20;
	/*swap01(a, b);
	cout << "a=" << a << endl;	//a=10
	cout << "b=" << b << endl;	//b=20*/

	//2、地址传递
	//如果是地址传递,可以修改实参
	swap02(&a, &b);
	cout << "a=" << a << endl;	//a=20
	cout << "b=" << b << endl;	//b=10

	system("pause");
	return 0;
}

7.8 指针,数组,函数

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

示例:

myfun.h

#include<iostream>
using namespace std; 

void bubblesort(int * arr, int len);
void printArray(int* arr, int len);

myfun.cpp

#include"myfun.h"

//冒泡排序的函数
//参数一:数组的首地址,参数二:数组长度
void bubblesort(int * arr, int len)
{
	int *p = arr;
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

void printArray(int* arr, int len)
{
	for (int i = 0; i < len; i++)
		cout << arr[i] << " ";
}

main.cpp

#include"myfun.h"

int main()
{
	//1、先创建数组
	int arr[10] = { 4,3,6,9,1,2,10,8,7,5 };
	int len = sizeof(arr) / sizeof(arr[0]);
	//2、创建函数,实现冒泡排序
	bubblesort(arr, len);

	//3、打印排序后的数组

	printArray(arr, len);
	system("pause");
	return 0;
}

8. 结构体

8.1 结构体基本概念

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

8.2 结构体定义和使用

语法:

strcut 结构体名
{
    结构体成员列表
};

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

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

示例

#include<iostream>
#include<string>
using namespace std;
//1、创建学生数据类型:学生包括(姓名,年龄,分数)
struct Student
{
	string name;
	int age;
	int score;
}s3;

int main()
{
	//2、通过学生类型创建具体学生
	//struct关键字可以省略
	//2、1 strcut Student s1;
	struct Student s1;
	//给s1赋值
	s1.name = "胡图图";
	s1.age = 6;
	s1.score = 100;

	//2、2 strcut Student s2={...};
	struct Student s2 = { "小美",6,90 };

	//2、3 在定义结构体时顺便创建结构体变量
	s3.name = "壮壮";
	s3.age = 10;
	s3.score = 100;

	system("pause");
	return 0;
}

8.3 结构体数组

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

语法

struct 结构体名 数组名[元素个数]={{}, {}};

示例

#include<iostream>
#include<string>
using namespace std;
//结构体数组
//1、定义结构体
struct Student
{
	string name;
	int age;
	int score;
};

int main()
{
	//2、创建结构体数组
	//3、给结构体数组中的元素赋值
	struct Student stuArray[3] = {
		{"胡图图",6,100},
		{"小美",6,100},
		{"壮壮",10,100}
	};

	//更改元素值
	stuArray[2].name = "张小丽";
	stuArray[2].age = 36;

	//4、遍历结构体数组
	for (int i = 0; i < 3; i++)
	{
		cout << "姓名:" << stuArray[i].name << " "
			<< "年龄:" << stuArray[i].age << " "
			<< "成绩:" << stuArray[i].score << endl;
	}

	system("pause");
	return 0;
}

8.4 结构体指针

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

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

示例:

struct student
{
	string name;
	int age;
	int score;
};
int main()
{
	//创建学生结构体变量
	student s = { "胡图图",6,100 };

	//通过指针指向结构体变量
	student * p = &s;

	//通过指针访问结构体变量中的数据
	//通过结构体指针访问结构体中的属性,需要通过->访问
	cout << "姓名:" << p->name << " " 
		<< "年龄:" << p->age << " " 
		<< "分数:" << p->score << endl;

	system("pause");
	return 0;
}

8.5 结构体嵌套结构体

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

例如:每个老师辅导一个学生,一个老师的结构体中可以包含一个学生的结构体

示例

//定义学生的结构体
struct student 
{
	string name;
	int age;
	int score;
};
//定义老师的结构体
struct teacher
{
	int id;
	string name;
	int age;
	struct student stu;
};

int main()
{
	//创建老师
	teacher t;
	t.id = 11100;
	t.name = "健康哥哥";
	t.age = 26;
	t.stu.name = "胡图图";
	t.stu.age = 6;
	t.stu.score = 100;

	cout << "老师姓名:" << t.id << " " << "老师编号:" << t.id
		<< " " << "老师年龄:" << t.age << " " 
		<< "老师辅导的学生姓名:" << t.stu.name << " "
		<< "学生年龄:" << t.stu.age << " " << "学生成绩" << t.stu.score << endl;

	system("pause");
	return 0;
}

8.6 结构体作函数参数

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

传递方式有两种:

  • 值传递
  • 地址传递

示例:

#include<iostream>
#include<string>
using namespace std;
//定义学生结构体
struct student
{
	//姓名
	string name;
	//年龄
	int age;
	//分数
	int score;
};
//值传递
void printStudent1(student s)
{
	//值传递中不会修改实参
	cout<<"子函数中 姓名:" << s.name
		<< " " << "年龄:" << s.age << " " << "分数:" << s.score << endl;
}

//地址传递
void printStudent2(student * s)
{
	//地址传递可以修改实参
	s->name = "小美";
	cout << "子函数2中 姓名:" << s->name << " " 
		<< "年龄:" << s->age << " " << "分数:" << s->score << endl;
}
int main()
{
	//将学生传入到一个参数中,打印学生身上的所有信息

	//创建结构体变量
	struct student s;
	s.name = "胡图图";
	s.age = 6;
	s.score = 99;

	printStudent1(s);

	cout << "在main函数中打印 姓名:" << s.name
		<< " " << "年龄:" << s.age << " " << "分数:" << s.score << endl;

	printStudent2(&s);
	cout << "在main函数中打印 姓名:" << s.name
		<< " " << "年龄:" << s.age << " " << "分数:" << s.score << endl;

	system("pause");
	return 0;
}

总结:如果不想修改主函数中的数据,用值传递,否则用地址传递

8.7 结构体中const使用场景

作用:用const来防止误操作

示例

struct student
{
	//姓名
	string name;
	//年龄
	int age;
	//分数
	int score;
};

//值传递会占用内存,会复制新的副本出来
//改成地址传递,可以减少内存空间,而且不会复制新的副本出来,但是地址传递会修饰实参
//为了防止误操作,可以使用const修饰
void printStudent(const student *s)
{
	cout << "姓名:" << s->name << " " 
		<< "年龄:" << s->age << " " << "分数:" << s->score << endl;
}
int main()
{
	student s = { "胡图图",6,100 };

	//通过函数打印结构体信息
	printStudent(s);

	system("pause");
	return 0;
}

8.8 结构体案例

案例1:三个老师带五个学生

#include<iostream>
#include<string>
#include<ctime>
using namespace std;
//学生结构体定义
struct Student 
{
	string name;
	int score;
};

//老师结构体定义
struct Teacher 
{
	string tName;
	struct Student sArray[5];
};

//给老师和学生赋值的函数
void allocateSpace(Teacher tArray[], int len)
{
	string nameSeed = "ABCDE";
	//给老师开始赋值
	for (int i = 0; i < len; i++)
	{
		tArray[i].tName = "Teacher_";
		tArray[i].tName += nameSeed[i];
		//通过循环给每名老师带的学生赋值
		for (int j = 0; j < 5; j++)
		{
			tArray[i].sArray[j].name = "Student_";
			tArray[i].sArray[j].name += nameSeed[j];


			int random = rand() % 100 + 1;
			tArray[i].sArray[j].score = random;
		}
	}

}

//打印所有信息的函数
void printInfo(Teacher tArray[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << "老师姓名:" << tArray[i].tName << endl;

		for (int j = 0; j < 5; j++)
		{
			cout << "\t学生姓名:" << tArray[i].sArray[j].name << " "
				<< "考试分数:" << tArray[i].sArray[j].score << endl;
		}
	}
}

int main()
{
	//添加随机数种子
	srand((unsigned int)time(NULL));

	//创建3名老师的数组
	Teacher tArray[3];

	//通过函数给3名老师的信息复制,并给老师带的学生信息赋值
	int len = sizeof(tArray) / sizeof(tArray[0]);
	allocateSpace(tArray, len);

	//打印所有老师及所带的学生信息
	printInfo(tArray, len);
	system("pause");
	return 0;
}

案例2

设计一个英雄的结构体,包括成员姓名,年龄,性别

创建结构体数组,数组中存放5名英雄。

通过冒泡排序,将数组中的英雄按照年龄升序排序,最终打印结果

#include<iostream>
#include<string>
#include<ctime>
using namespace std;

//设计英雄结构体
struct hero 
{
	string name;
	int age;
	string sex;
};

//对数组进行排序,按照年龄进行升序排序
void bubbleSort(hero heroArray[], int len)
{
	for (int i = 0; i < len-1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
			if (heroArray[j].age > heroArray[j + 1].age)
			{
				hero temp = heroArray[j];
				heroArray[j] = heroArray[j + 1];
				heroArray[j + 1] = temp;
			}
		}
	}
}
//对排序结果打印输出
void printinfo(hero heroArray[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << "姓名:" << heroArray[i].name << " "
			<< "年龄:" << heroArray[i].age << " "
			<< "性别:" << heroArray[i].sex << endl;
	}
}
int main()
{
	//创建数组存放5名英雄
	hero heroArray[5] = {
		{"刘备",23,"男"},
		{"关羽",22,"男"},
		{"张飞",20,"男"},
		{"赵云",21,"男"},
		{"貂蝉",19,"女"},
	};

	int len = sizeof(heroArray) / sizeof(heroArray[0]);
	bubbleSort(heroArray, len);
	printinfo(heroArray, len);
	system("pause");
	return 0;
}

二. C++面向对象编程技术

9. 内存分区模型

C++程序在执行时,将内存大方向划分为四个区域

  • 代码区:存放函数体的二进制代码,由OS进行管理
  • 全局区:存放全局变量和静态变量以及常量
  • 栈区:由编译器自动分配释放,存放函数的参数值,局部变量等
  • 堆区:由程序员分配和释放,若程序员不释放,程序结束时由OS回收

存在的意义:不同区域存放的数据,赋予不同的生命周期

9.1 程序运行前

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

代码区

  • 存放CPU执行的机器指令
  • 代码区是共享,共享的目的是对于频繁被执行的程序,只需要在内存中有一份代码即可
  • 代码区是可读的,使其可读的原因是防止程序意外的修改指令

全局区

  • 全局变量和静态变量(static关键字修饰)存在在此
  • 全局区还包含了常量区,字符串常量和其他常量也存放于此
  • 该区域是数据在程序结束后由OS释放

总结:

  • C++中在程序运行前分为全局区和代码区
  • 代码区的特点是共享和只读
  • 全局区中存放全局变量、静态变量、常量
  • 常量区中存放const修饰的全局常量和字符串常量

9.2 程序运行后

栈区

  • 由编译器自动分配释放,存放函数的参数值、局部变量等
  • 不要返回局部变量的地址,栈区开辟的数据由编译器自动释放

示例

//栈区注意事项——不要返回局部变量的地址
//栈区的数据由编译器管理开辟和释放
int *  func()
{
	int a = 10;		//局部变量	存放在栈区,栈区的数据在函数执行完后自动释放
	return &a;		//返回局部变量的地址
}

int main()
{
	//接收func函数的返回值
	int * p = func();
	cout << *p << endl;		//10 编译器做了保留
	cout << *p << endl;		//error

	system("pause");
	return 0;
}

堆区

  • 由程序员分配释放,若程序员不释放,程序结束时由OS回收
  • 在C++中主要利用new在堆区中开辟内存

示例

int * func()
{
	//利用new关键字 可以将数据开辟到堆区
	//指针本质也是局部变量,放在栈上,指针保存的数据放在堆区
	int * p = new int(10);
	return p;
}
int main()
{
	int * p = func();

	cout << *p << endl;
	cout << *p << endl;
	system("pause");
	return 0;
}

总结:

  • 堆区数据由程序员管理开辟和释放
  • 堆区数据利用new关键字进行开辟内存

9.3 new操作符

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

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

语法

new 数据类型

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

示例:

int * myfunc()
{
	//在堆区创建整型数据
	int * p = new int(10);
	return p;
}
void test01()
{
	int * p = myfunc();
	cout << *p << endl;
	cout << *p << endl;
	//如果想释放堆区的数据,利用关键字delete
	delete p;
	//cout << *p << endl;	引发了异常: 读取访问权限冲突。
}

//在堆区利用new开辟数组
void test02()
{
	//在堆区创建10个整型数据的数组
	//new int[10] 返回数组首地址
	int * arr = new int[10];

	for (int i = 0; i < 10; i++)
		arr[i] = i + 100;
	for (int i = 0; i < 10; i++)
		cout << arr[i] << endl;
	//释放堆区数组
	//释放数据的时候,要加[]
	delete[] arr;
}
int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}

10. 引用

10.1 引用的基本使用

作用:给变量起别名

语法

数据类型 & 别名=原名

示例

int main()
{
	int a = 10;
	//创建引用
	int &b = a;

	cout << "a=" << a << endl;
	cout << "b=" << b << endl;

	b = 100;
	cout << "a=" << a << endl;	//100
	cout << "b=" << b << endl;	//100

	system("pause");
	return 0;
}

10.2 引用注意时项

  • 引用必须初始化
  • 引用在初始化后,不可以被改变

示例:

int main()
{
	//1、引用必须初始化
	//int &b=a;error

	//2、引用在初始化后,不可以发生改变
	int a = 10;
	int & b = a;
	int c = 20;
	//int &b = c;error


	system("pause");
	return 0;
}

10.3 引用作函数参数

作用:函数传参时,可以利用引用让形参修饰实参

优点:可以简化指针修饰实参

示例:

//交换函数
//1、值传递
void swap1(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
}

//2、地址传递
void swap2(int * a, int *b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}
//3、引用传递
void swap3(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}

int main()
{
	int a = 10;
	int b = 20;
	swap1(a, b);	//值传递形参不会修饰实参
	cout << "a=" << a << endl;	//a=10
	cout << "b=" << b << endl;	//b=20

	swap2(&a, &b);	//地址传递形参会修饰实参
	cout << "a=" << a << endl;	//a=20
	cout << "b=" << b << endl;	//b=10

	a = 10;
	b = 20;
	swap3(a, b);	//引用传递,形参会修饰实参
	cout << "a=" << a << endl;	//a=20
	cout << "b=" << b << endl;	//b=10

	system("pause");
	return 0;
}

10.4 引用作函数返回值

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

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

用法:函数调用作为左值

示例

//引用作函数的返回值
//1、不要返回局部变量的引用

int & test01()
{
	int a = 10;	//局部变量存放在四区中的栈区
	return a;
}

//2、函数的调用可以作为左值
int & test02()
{
	static int a = 10; //静态变量,存放在全局区,全局区上的数据由系统释放
	return a;
}
int main()
{
	int &ref1 = test01();
	cout << "ref1=" << ref1 << endl;
	cout << "ref1=" << ref1 << endl;	//error

	int &ref2 = test02();
	cout << "ref2=" << ref2 << endl;
	cout << "ref2=" << ref2 << endl;

	test02() = 1000;		//如果函数的返回值是引用,这个函数调用可以作为左值
	cout << "ref2=" << ref2 << endl;		//1000
	cout << "ref2=" << ref2 << endl;
	system("pause");
	return 0;
}

10.5 引用的本质

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

//发现是引用,转化为int * const ref=&a
void func(int & ref)
{
    ref=1000;//ref是引用,转化为*ref = 1000;
}
int main()
{
    int a = 10;
    //指针常量指向不可以改,但是指向的内容可以修改,这就解释了2.4中可以作为左值
    int & ref = a;	//自动转化为int * const ref = &a;
    ref = 100;	//内部发现ref是引用,自动转化为 * ref = 100
    
}

10.6 常量引用

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

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

示例

//打印数据函数
void showValue(const int & val)
{
	//val = 1000;	error
	cout << "val=" << val << endl;
}
int main()
{
	//使用场景:用来修饰形参,防止误操作
	/*
	int a = 10;
	//int &ref = 10; error 因为10在常量区,引用必须引用一块合法的内存空间
	//加上const后,编译器将代码修改为
	//int temp = 10;
	//int &ref = temp;
	
	const int & ref = 10;	
	//ref = 20; error 加上const以后变为只读,不可以修改
	*/

	int a = 100;
	showValue(a);
	cout << "a=" << a << endl;		//1000
	system("pause");
	return 0;
}

11. 函数进化版

11.1 函数默认参数

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

语法

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

示例

//如传入数据则用自己数据,否则用默认值
int func(int a, int b=20, int c=30)
{
	return a + b + c;
}

//注意事项
//1、如果某个位置已经有了默认参数,则从这个位置开始,从左往后必须有默认值
//2、如果函数声明有默认参数,则函数实现就不能有默认参数了
int main()
{
	cout << func(10) << endl;	//60
	cout << func(10, 30) << endl;	//70
	system("pause");
	return 0;
}

11.2 函数占位参数

C++函数的形参列表里可以有占位参数,用来作占位,调用函数时必须填补该位置

语法

返回值类型 函数名(数据类型){}

示例

void func(int a,int)
{
	cout << "this is func" << endl;
}
int main()
{
	func(10, 10);

	system("pause");
	return 0;
}

11.3 函数重载

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

函数重载满足条件:

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

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

示例

void func()
{
	cout << "func的调用" << endl;
}
void func(int a)
{
	cout << "func的调用!" << endl;
}

int main()
{
	func();	//func的调用
	func(10);	//func的调用!
	system("pause");
	return 0;
}

函数重载的注意事项:

  • 引用作为重载条件
  • 函数重载碰到函数默认参数

示例:

//1、引用作为重载的条件
void func(int & a)
{
	cout << "func(int & a)的调用" << endl;
}
void func(const int & a)
{
	cout << "const func(int & a)的调用" << endl;
}

//2、函数重载碰到默认参数,会出现二义性,要尽量避免
void func2(int a,int b=10)
{
	cout << "void func2(int a)的调用" << endl;
}
void func2(int a)
{
	cout << "void func2(int a)的调用" << endl;
}
int main()
{
	//int a = 10;
	//func(a);	//func(int & a)的调用

	func(10);	//const func(int & a)的调用
	system("pause");

	//func2();	//error
	return 0;
}

12. 类和对象

C++面向对象的三大特性是:封装,继承,多态

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

12.1 封装

12.1.1 封装的意义

封装的意义:

  • 将属性和行为作为一个整体,变现生活中的事物
  • 将属性和行为加以权限控制

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

语法

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

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

const double PI = 3.14;		//圆周率

class Circle
{
	//访问权限
public:			//公共权限
	//属性
	int m_r;	//半径
	//行为:获取圆的周长
	double calculateZC()
	{
		return 2 * PI*m_r;
	}
};


int main()
{
	//通过圆类 创建具体的圆(对象)
	Circle c1;
	c1.m_r = 10;

	cout << "圆的周长为:" << c1.calculateZC() << endl;
	system("pause");
	return 0;
}

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

//设计学生类
class Student
{
	//访问权限
public:
	//属性
	string m_Name;
	int m_ID;
	//行为:显示姓名和学号
	void showStudent()
	{
		cout << "姓名:" << m_Name << " 学号:" << m_ID << endl;
	}
	//行为:给姓名赋值
	void setName(string name)
	{
		m_Name = name;
	}	
	void setID(int id)
	{
		m_ID = id;
	}
};
int main()
{
	//实例化:创建一个具体的学生
	Student s1;
	//s1.m_Name = "胡图图";
	s1.setName("胡图图");
	//s1.m_ID = 1;
	s1.setID(1);
	//显示学生信息
	s1.showStudent();

	Student s2;
	s2.m_Name = "小美";
	s2.m_ID = 2;
	//显示学生信息
	s2.showStudent();
	system("pause");
	return 0;
}
  • 类中的属性和行为 统称为成员
  • 属性/成员属性/成员变量
  • 行为/成员函数/成员方法

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

访问权限有三种:

  • public:公共权限
  • protected:保护权限
  • private:私有权限

示例

//公共权限public	 成员 类内可以访问,类外可以访问
//保护权限protected  成员 类内可以访问,类外不可以访问,子类可以访问父类中保护内容
//私有权限private	 成员 类内可以访问,类外不可以访问,子类不可以访问父类中保护内容

class Person
{
public:
	//公共权限
	string m_Name;
protected:
	//保护权限
	string m_Car;
private:
	int m_Password;

public:
	void func()
	{
		m_Name = "胡英俊";
		m_Car = "迈巴赫";
		m_Password = 1111;
	}
};
int main()
{
	//实例化具体对象
	Person p1;
	p1.m_Name = "壮壮爸爸";		//在类外只能访问到公共权限
	p1.func();
	system("pause");
	return 0;
}

12.1.2 struct和class的区别

在C++中,struct和class唯一的区别就在于默认的访问权限不同

  • struct默认权限为公有
  • class默认权限为私有

示例

class C1
{
	int m_A;	//默认权限是 私有
};

struct C2
{
	int m_A;	//默认权限是 公有
};
int main()
{
	C1 c1;
	//c1.m_A = 1; error 因为私有权限类外不可以访问
	C2 c2;
	c2.m_A = 10;
	system("pause");
	return 0;
}

12.1.3 成员属性设置为私有

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

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

示例

//设计人 类
class Person
{
public:
	//设置姓名
	void setName(string name)
	{
		m_Name = name;
	}
	//获取姓名
	string getName()
	{
		return m_Name;
	}

	获取年龄	只读
	//int getAge()
	//{
	//	m_Age = 36;	//初始化为36
	//	return m_Age;
	//}
	//获取年龄 可读可写,如果想修改,年龄的范围必须是0-150之间
	int getAge()
	{
		return m_Age;
	}

	//设置年龄	只写
	void setAge(int age)
	{
		if (age < 0 || age>150)
		{
			m_Age = 0;
			cout << "输入数据有误!" << endl;
			return;
		}
		m_Age = age;
	}

	//设置情人 只写
	void setLover(string lover)
	{
		m_Lover = lover;
	}

private:
	string m_Name;	//姓名 可读可写
	int m_Age;		//年龄 只读
	string m_Lover; //情人 只写
};
int main()
{
	Person p;
	p.setName("胡英俊");
	cout << "姓名为:" << p.getName() << endl;
	cout << "年龄为:" << p.getAge << endl;

	p.setLover("张晓丽");
	system("pause");
	return 0;
}

练习案例1:设计立方体

设计立方体类(Cube),求出立方体的面积和体积,分别用全局函数和成员函数判定两个立方体是否相等

//创建立方体的类
class Cube
{
public:
	//设置长
	void setL(int l)
	{
		m_L = l;
	}
	//获取长
	int getL()
	{
		return m_L;
	}
	//设置宽
	void setW(int w)
	{
		m_W = w;
	}
	//获取宽
	int getW()
	{
		return m_W;
	}
	//设置高
	void setH(int h)
	{
		m_H = h;
	}
	//获取高
	int getH()
	{
		return m_H;
	}
	//获取立方体的面积
	int calculateS()
	{
		return 2 * m_L*m_W + 2 * m_L*m_H + 2 * m_H*m_W;
	}
	//获取立方体的体积
	int calculateV()
	{
		return m_L * m_W*m_H;
	}

	//利用成员函数判断两个立方体是否相等
	bool isSameByClass(Cube &c)		//只传入一个参数是因为调用本身就是个Cube
	{
		if (m_L == c.getL() && m_W == c.getW()&&m_H == c.getH())
			return true;
		else
			return false;
	}

private:
	int m_L;
	int m_W;
	int m_H;
};

//利用全局函数判断两个立方体是否相等
bool isSame(Cube &c1, Cube &c2)		//用引用方式传入就避免了值传递的数据拷贝
{
	if (c1.getL() == c2.getL() && c1.getW() == c2.getW() && c1.getH() == c2.getH())
		return true;
	else
		return false;
}
int main()
{
	//实例化一个立方体对象
	Cube c1;
	c1.setL(10);
	c1.setW(10);
	c1.setH(10);

	cout << "c1的面积为:" << c1.calculateS() << endl;
	cout << "c1的体积为:" << c1.calculateV() << endl;

	//实例化第二个立方体
	Cube c2;
	c2.setL(10);
	c2.setW(10);
	c2.setH(10);

	//bool ret = isSame(c1, c2);
	bool ret = c1.isSameByClass(c2);		//利用成员函数判断
	if (ret)
	{
		cout << "c1和c2是相等的" << endl;
	}
	else
		cout << "c1和c2是不等的" << endl;

	system("pause");
	return 0;
}

练习案例2:点和圆的关系

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

point.h

#pragma once		//防止头文件重复包含
#include<iostream>
using namespace std;

//创建点类
class Point
{
public:
	//设置x
	void setX(int x);
	//获取x
	int getX();

	//设置y
	void setY(int y);
	//获取y
	int getY();
private:
	int m_X;
	int m_Y;
};

point.cpp

#include"point.h"

//设置x
void Point::setX(int x)
{
	m_X = x;
}
//获取x
int Point::getX()
{
	return m_X;
}

//设置y
void Point::setY(int y)
{
	m_Y = y;
}
//获取y
int Point::getY()
{
	return m_Y;
}

circle.h

#pragma once
#include<iostream>
#include"point.h"
using namespace std;

//只需要留下函数的声明和成员属性
//创建圆类
class Circle
{
public:
	//设置半径
	void setR(int r);
	//获取半径
	int getR();
	//设置圆心
	void setCenter(Point center);
	//获取圆心
	Point getCenter();

private:
	int m_R;//半径
	//在类中可以让另外一个类作为本类的成员
	Point m_Center;	//圆心
};

circle.cpp

#include"circle.h"
//只需要留下函数的实现

//设置半径
void Circle::setR(int r)
{
	m_R = r;
}
//获取半径
int Circle::getR()
{
	return m_R;
}
//设置圆心
void Circle::setCenter(Point center)
{
	m_Center = center;
}
//获取圆心
Point Circle::getCenter()
{
	return m_Center;
}

main.cpp

#include<iostream>
#include"point.h"
#include"circle.h"
using namespace std;

创建点类
//class Point
//{
//public:
//	//设置x
//	void setX(int x)
//	{
//		m_X = x;
//	}
//	//获取x
//	int getX()
//	{
//		return m_X;
//	}
//
//	//设置y
//	void setY(int y)
//	{
//		m_Y = y;
//	}
//	//获取y
//	int getY()
//	{
//		return m_Y;
//	}
//
//private:
//	int m_X;
//	int m_Y;
//};
//
创建圆类
//class Circle
//{
//public:
//	//设置半径
//	void setR(int r)
//	{
//		m_R = r;
//	}
//	//获取半径
//	int getR()
//	{
//		return m_R;
//	}
//	//设置圆心
//	void setCenter(Point center)
//	{
//		m_Center = center;
//	}
//	//获取圆心
//	Point getCenter()
//	{
//		return m_Center;
//	}
//
//private:
//	int m_R;//半径
//	//在类中可以让另外一个类作为本类的成员
//	Point m_Center;	//圆心
//};

//判断点和圆的关系
void isInCircle(Circle &c, Point &p)	//用引用方式传递可以避免值传递过程中数据复制问题
{
	//计算两点之间距离的平方
	int distance =
		(c.getCenter().getX() - p.getX())*(c.getCenter().getX() - p.getX()) +
		(c.getCenter().getY() - p.getY())*(c.getCenter().getY() - p.getY());
	
	//计算半径的平方
	int rDistance = c.getR()*c.getR();

	//判断关系
	if (distance == rDistance)
		cout << "点在圆上" << endl;
	else if (distance > rDistance)
		cout << "点在圆外" << endl;
	else
		cout << "点在圆内" << endl;
}
int main()
{
	//创建圆
	Circle c;
	c.setR(10);
	Point center;	//创建圆心
	center.setX(10);
	center.setY(0);
	c.setCenter(center);

	//创建点
	Point p;
	p.setX(10);
	p.setY(10);

	//判断关系
	isInCircle(c, p);
	system("pause");
	return 0;
}

12.2 对象的初始化和清理

C++中的每个对象会有初始设置以及对象销毁前的清理数据的设置

12.2.1 构造函数与析构函数

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

  • 一个对象或者变量没有初始化,对其使用的后果是位置的
  • 同样使用完一个对象或者变量,没有及时清理,也会造成一定的安全问题

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

  • 构造函数:主要作用在创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无需手动调用
  • 析构函数:主要作用在用户销毁前系统自动调用,执行一些清理工作

构造函数语法:

类名(){}
  • 构造函数,没有返回值也不写void
  • 函数名和类名相同
  • 构造函数可以有参数,因此可以发生重载
  • 程序在调用对象时会自动调用构造,无需手动调用,而且只会调用一次

析构函数语法:

~类名(){}
  • 析构函数,没有返回值也不写void
  • 析构函数名称和类名称相同,在名称前加~
  • 析构函数不可以有参数,因此不可以发生重载
  • 程序在对象销毁前会自动调用析构函数,无需手动调用,而且只会调用一次

示例:

//1、构造函数 进行初始化操作
class Person1 
{
public:
	//构造函数
	Person1()
	{
		cout << "Person 构造函数的调用" << endl;
	}
	//2、析构函数 进行清理的操作
	~Person1()
	{
		cout << "Person 析构函数的调用" << endl;
	}

};

//构造和析构是必须有的实现,如果未提供,编译器会提供一个空实现的构造和析构
void test05()
{
	Person1 p;	//在栈上的数据,test05执行完毕,释放这个对象
}

int main()
{
	test05();
	//Person1 p;		

	system("pause");
	return 0;
}

12.2.2 构造函数的分类和调用

两种分类方式:

  • 按参数分为:有参构造和无参构造
  • 按类型分为:普通构造和拷贝构造

三种调用方式:

  • 括号法
  • 显示法
  • 隐式转换法

示例:

//分类
class Person9
{
public:
	//无参构造(默认构造)
	Person9()
	{
		cout << "Person9的无参构造函数调用" << endl;
	}
	//有参构造
	Person9(int a)
	{
		age = a;
		cout << "Person9的有参构造函数调用" << endl;
	}
	//拷贝构造函数
	Person9(const Person9 &p)		//引用方式传递
	{
		//将传入人身上所有属性,拷贝到我身上
		cout << "Person9的拷贝构造函数调用" << endl;
		age = p.age;
	}

	~Person9()
	{
		cout << "Person9的析构函数调用" << endl;
	}
	int age;
};

//调用
void test03()
{
	//1、括号法
	//调用默认构造函数的时候不要加()
	//Person9 p1();编译器会认为是一个函数的声明,不会认为在创建对象
/*
	Person9 p1;	//默认构造函数调用
	Person9 p2(10);	//调用有参构造函数
	Person9 p3(p2);	//调用拷贝构造函数

	cout << "P2的年龄:" << p2.age << endl;	//10
	cout << "P3的年龄:" << p3.age << endl;	//10
*/
	
	//2、显示法
	//不要利用拷贝构造函数 初始化匿名对象
	//Person(p3); 编译器会认为是对象声明
/*
	Person9 p1;
	Person9 p2 = Person9(10);	//有参构造
	Person9 p3 = Person9(p2);	//拷贝构造

	Person9(10);	//匿名对象 特定:当前行执行结束后,系统会立即回收掉匿名对象
*/
	
	//3、隐式转换法
	Person9 p4 = 10;	//相当于 Person9 p4=Person(10) 有参构造
	Person9 p5 = p4;	//拷贝构造
}
int main()
{
	test03();
	system("pause");
	return 0;
}

12.2.3 拷贝构造函数调用时机

C++中拷贝函数调用时机通常有三种情况

  • 使用一个已经创建完毕的对象来初始化一个新对象
  • 值传递的方法给函数参数传值
  • 以值方式返回局部对象

示例

class Person0
{
public:
	Person0()
	{
		cout << "Person0的默认构造函数调用" << endl;
	}
	Person0(int age)
	{
		m_Age = age;
		cout << "Person0的有参构造函数调用" << endl;
	}
	Person0(const Person0 &p)
	{
		m_Age = p.m_Age;
		cout << "Person0的拷贝构造函数调用" << endl;
	}
	~Person0()
	{
		cout << "Person0的析构函数调用" << endl;
	}
	int m_Age;
};

//1、使用一个已经创建完毕的函数来初始化一个新对象
void test002()
{
	Person0 p1(20);
	Person0 p2(p1);
	cout << "P2 的age:" << p2.m_Age << endl;
}

//2、值传递的方式给函数参数传值
void doWork(Person0 p)	//值传递
{

}
void test003()
{
	Person0 p;
	doWork(p);
}
//3、值传递返回局部对象
Person0 doWork2()
{
	Person0 p1;
	cout << (int *)&p1 << endl;		//0053FA64
	return p1;	//返回的不是p1,返回 是调用拷贝构造函数之后复制的副本
}
void test004()
{
	Person0 p = doWork2();
	cout << (int *)&p << endl;		//0053FB5C
}
int main()
{
	test004();
	system("pause");
	return 0;
}

12.2.4 构造函数调用规则

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

  • 默认构造函数(无参,函数体为空)
  • 默认析构函数(无参,函数体为空)
  • 默认拷贝构造函数,对属性进行值拷贝

构造函数调用规则如下:

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

示例:

//1、创建一个类,C++编译器会给每个类添加至少3个函数
//默认构造(空实现)
//析构函数(空实现)
//拷贝构造(值拷贝)

//2、如果我们写了有参构造函数,编译器就不会再提供默认构造,依然提供拷贝构造

//3、如果我们写了拷贝构造函数,编译器就不会提供任何构造函数
class Person11
{
public:
	//Person11()
	//{
	//	cout << "Person11的默认构造函数调用" << endl;
	//}

	Person11(int age)
	{
		m_Age = age;
		cout << "Person11的有参构造函数调用" << endl;
	}
	//Person11(const Person11 & p)
	//{
	//	m_Age = p.m_Age;
	//	cout << "Person11的拷贝构造函数调用" << endl;
	//}

	~Person11()
	{
		cout << "Person11析构函数调用" << endl;
	}

	int m_Age;
};
//void test0001()
//{
//	Person11 p;
//	p.m_Age = 18;
//	Person11 p2(p);
//	cout << "p2的age" << p2.m_Age << endl;	//p2的age18
//}
void test0002()
{
	Person11 p(28);
	Person11 p1(p);
	cout << "p1的年龄:" << p1.m_Age << endl;	//28
}
int main()
{
	//test0001();
	test0002();
	system("pause");
	return 0;
}

12.2.5 深拷贝和浅拷贝

浅拷贝:简单的赋值拷贝操作,编译器提供的简单赋值操作 eg:m_Height = p.m_Height

深拷贝:用new在堆区重新申请空间,进行拷贝操作 eg:m_Height = new int(*p.m_Height);

浅拷贝会出现的问题:堆区的内存重复释放。

解决方法:利用深拷贝

示例:

class Person12
{
public:
	Person12()
	{
		cout << "Person的默认构造函数调用" << endl;
	}
	Person12(int age , int height)
	{
		m_age = age;
		//利用new操作符在堆区开辟数据
		//利用new创建的数据,会返回该数据对应的类型的指针
		//堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符delete
		m_Height = new int(height);	
		cout << "Person的有参构造函数调用" << endl;
	}

	//自己实现拷贝构造函数,解决浅拷贝带来的问题:堆区数据重复释放导致程序中断
	Person12(const Person12 & p)
	{
		cout << "Person拷贝构造函数的调用";
		m_age = p.m_age;
		//m_Height = p.m_Height;	编译器默认实现就是这行代码
		//深拷贝 new 一个新的堆区
		m_Height = new int(*p.m_Height);
	}

	~Person12()
	{
		//析构代码的作用:将堆区开辟的数据作释放操作
		if (m_Height)
		{
			delete m_Height;
			m_Height = NULL;	//防止野指针的出现
		}
		cout << "Person析构函数调用" << endl;
	}
	int m_age;
	int *m_Height;	//身高 ,用指针将其数据开辟到堆区
};

void test0111()
{
	Person12 p1(18, 160);
	//p1.m_Height是指针,需要解引用
	cout << "P1的年龄:" << p1.m_age << "身高为:" << * p1.m_Height << endl;
	
	Person12 p2(p1);
	cout << "P2的年龄:" << p2.m_age << "身高为:" << * p2.m_Height << endl;
}
int main()
{
	test0111();	//Person的有参构造函数调用;P1的年龄:18;P2的年龄:18;Person析构函数调用
	system("pause");
	return 0;
}

12.2.6 初始化列表

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

语法

构造函数(): 属性1(1),属性2(2).....{}

示例:

class Person413
{
public:
	//传统初始化操作
	/*
	Person413(int a, int b, int c)
	{
		m_A = a;
		m_B = b;
		m_C = c;
	}
	*/
	//初始化列表来初始化属性
	Person413(int a, int b, int c) :m_A(a), m_B(b), m_C(c)
	{
		//可以为空
	}
	int m_A;
	int m_B;
	int m_C;
};

void test413()
{
	//Person413 p(10, 20, 30);
	Person413 p(30, 20, 10);
	cout << "m_A= " << p.m_A << endl;
	cout << "m_B= " << p.m_B << endl;
	cout << "m_C= " << p.m_C << endl;
}
int main()
{
	test413();
	system("pause");
	return 0;
}

12.2.7 类对象作为类成员

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

例如:

class A{}
class B
{
    A a;
}

B类中有对象A作为成员,A为成员对象

先构造A,再构造B;

销毁时,先销毁B,再销毁A

示例:

//手机类
class Phone
{
public:
	Phone(string pname)
	{
		m_PName = pname;
		cout << "Phone的构造函数调用" << endl;
	}
	~Phone()
	{
		cout << "这是Phone的析构函数" << endl;
	}
	string m_PName;
};
//人类
class Person414
{
public:
	//初始化列表来初始化属性
	//m_Phone(pname) 相当于 Phone m_Phone = pname;(隐式转换法)
	//相当于 Phone m_Phone=Phone(pname)(显示)
	Person414(string name, string pname):m_Name(name),m_Phone(pname)	
	{
		cout << "Person的构造函数调用" << endl;
	}
	~Person414()
	{
		cout << "Person的析构函数" << endl;
	}
	//姓名
	string m_Name;
	//手机
	Phone m_Phone;
};

//当其他类对象作为本类对象成员时,先构造其他类对象,再构造自身
//析构顺序:先销毁自身,再销毁成员对象
void test414()
{
	Person414 p("胡图图", "苹果11");
	cout << p.m_Name << "拿着:" << p.m_Phone.m_PName << endl;	//胡图图拿着:苹果11
}

int main()
{
	test414();	
	//Phone的构造函数调用	Person的构造函数调用
	//Person的析构函数	这是Phone的析构函数
	system("pause");
	return 0;
}

12.2.8 静态成员

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

静态成员分别为:

  • 静态成员变量
    • 所有对象共享同一份数据
    • 在编译阶段分配内存
    • 类内声明,类外初始化
  • 静态成员函数
    • 所有对象共享同一个函数
    • 静态成员函数只能访问静态成员变量

示例1:静态成员变量

class Person415
{
public:
	//静态成员变量特点
	/*
	1、所有对象都共享同一份数据
	2、在编译阶段就分配内存
	3、类内声明,类外初始化
	*/
	
	static int m_A;

	//静态成员变量也是有访问权限的
private:
	static int m_B;
};
//3、类内声明,类外初始化
int Person415::m_A = 100;

int Person415::m_B = 200;
void test415()
{
	Person415 p;
	cout << p.m_A << endl;		//100
	//1、所有对象都共享同一份数据
	Person415 p2;
	p2.m_A = 200;
	cout << p.m_A << endl;		//200
}

void test4152()
{
	//静态成员变量不属于某个对象,所有对象都共享同一份数据
	//因此静态成员变量有两种访问方式
	//通过对象进行访问
	Person415 p;
	cout << p.m_A << endl;	//100
	//通过类名进行访问
	cout << Person415::m_A << endl;	//100
	//cout << Person415::m_B << endl;	//error 类外访问不到私有静态成员变量
}
int main()
{
	test4152();

	system("pause");
	return 0;
}

示例2:静态成员函数

//所有对象共享同一个函数
//静态成员函数只能访问静态成员变量

class Person416
{
public:
	//静态成员函数
	static void func416()
	{
		m_A = 100;	//静态成员函数可以访问静态成员变量
		//m_B = 100;	//error  因为静态成员函数不可以访问非静态成员变量,编译器无法区分是哪个对象的属性
		cout << "static void func416()的调用" << endl;
	}
	static int m_A;	//静态成员变量
	int m_B;	//非静态成员变量

	//静态成员函数也是有访问权限的
private:
	static void func4162()
	{
		cout << "static void func4162()的调用" << endl;
	}
};

//类内声明,类外初始化
int Person416::m_A = 0;

//有两种访问方式
void test416()
{
	//1、通过对象访问
	Person416 p;
	p.func416();

	//2、通过类名访问
	Person416::func416();
	//Person416::func4162();	//error  类外访问不到静态成员函数
}
int main()
{
	test416();
	system("pause");
	return 0;
}

12.3 C++对象模型和this指针

1. 成员变量和成员函数分开存储

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

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

class Person1
{

};
void test01()
{
	Person1 p;
	//空对象占用的内存为:sizeof(p)= 1
	//编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置
	//每个空对象也应该有一个独一无二的内存地址
	cout << "sizeof(p)= " << sizeof(p) << endl;
}
int main()
{
	test01();

	system("pause");
	return 0;
}

class Person1
{
	int m_A;	//非静态成员变量 属于类的对象上
	static int m_B;	//静态成员变量 不属于类的对象上

	void func(){}//非静态成员函数 不属于类的对象上
	

	static void func2(){}	//静态成员函数 不属于类的对象上
};

int Person1::m_B = 0;
void test01()
{
	Person1 p;
	//空对象占用的内存为:sizeof(p)= 1
	//编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置
	//每个空对象也应该有一个独一无二的内存地址
	cout << "sizeof(p)= " << sizeof(p) << endl;
}

void test02()
{
	Person1 p;
	//没有m_B成员变量:sizeof(p)= 4
	//有m_B成员变量:sizeof(p)= 4
	//有非静态成员函数后:sizeof(p)= 4
	//有静态成员函数后:sizeof(p)= 4
	cout << "sizeof(p)= " << sizeof(p) << endl;
}
int main()
{
	//test01();
	test02();

	system("pause");
	return 0;
}
  • 只有非静态成员变量在类的对象上

2. this指针概念

在C++中成员变量和成员函数是分开存储的

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

Q:这一块代码如何区分哪个对象调用自己?

A:C++通过特殊的对象指针,this指针:指向被调用的成员函数所属的对象

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

不需要被定义,直接使用即可

this指针的用途:

  • 当形参和成员变量同名时,可用this指针来区分
  • 在类的非静态成员函数中返回对象本身,可以使用return *this
class Person02
{
public:
	Person02(int age)
	{
		//1、解决名称冲突
		//this->age是非静态成员变量的age
		//this 指向的是 被调用的成员函数所属的对象 即p1(p1调用则指向p1)
		this->age = age;
	}
	//如果只是单纯的值传递:Person02 PersonAddAge(Person02 &p)
	//则只是做了数据复制,形参修饰不了实参
	Person02 & PersonAddAge(Person02 &p)
	{
		this->age += p.age;
		//this指向的是p2的指针,*this(解引用)指向的就是p2
		return *this;
	}
	int age;

};

void test4201()
{
	Person02 p1(18);
	cout << "p1的年龄是:" << p1.age << endl;
}

void test4202()
{
	Person02 p1(10);
	Person02 p2(10);
	//因为	void PersonAddAge(Person02 &p) 返回是void,不能二次调用
	//p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1); error
	
	//Person02 & PersonAddAge(Person02 &p) 返回值类型是一个引用类型的Person02
	p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);	//40
	cout << "p2的年龄:" << p2.age << endl;

}
//2、返回对象本身用 *this
int main()
{
	test4202();
	system("pause");
	return 0;
}

3. 空指针访问成员函数

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

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

class Person403
{
public:
	void showClassName()
	{
		cout << "this is Person class" << endl;
	}
	void showPersonAge()
	{
		//报错原因是因为传入的指针是NULL
		//cout << "age= " << this->m_Age << endl;
		if (this == NULL)
			return;
		cout << "age= " << this->m_Age << endl;
	}
	int m_Age;
};

void test403()
{
	Person403 * p = NULL;

	p->showClassName();

	p->showPersonAge();	
}
int main()
{
	test403();
	system("pause");
	return 0;
}

4. const修饰成员函数

常函数

  • 成员函数后加const后我们称这个函数为常函数
  • 常函数内不可以修改成员属性
  • 成员属性声明时加关键字mutable后,在常函数中依然可以修改

常对象

  • 声明对象前加const称该对象为常对象
  • 常对象只能调用常函数

实例

class Person404
{
public:
	//没有const,this->m_A=100是正确的
	//Person404 * const this 后,不可修改指针指向的值
	//在成员函数后面加const,修饰的是this指针,让指针指向的值也不可以修改
	//常函数
	void showPerson() const
	{
		//m_A = 100; error,相当于this->m_A = 100
		//this指针的本质是指针常量 指针的指向是不可以修改的,
		//但是this指向的值是可变的
		this->m_B = 100;
	}
	void funx()
	{

	}
	int m_A;
	//加关键字mutable 特殊变量,即使在常函数中,也可以修改这个值
	mutable int m_B;
};

void test404()
{
	Person404 p;
}
//常对象
void test4041()
{
	const Person404 p;	//在对象前加const就是常对象
	//p.m_A = 10;	//error 常对象不允许修改普通的成员变量
	p.m_B = 100;	//m_B是特殊值,在常对象下也可以修改

	//常对象只能调用常函数
	//因为普通成员函数可以修改普通成员变量,如果常对象调用普通函数
	//则常对象可以修改普通变量
	p.showPerson();
	//p.funx();	//error
}
int main()
{
	test404();
	system("pause");
	return 0;
}

12.4 友元

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

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

友元的关键字是friend

友元的三种实现方式:

  • 全局函数做友元
  • 类做友元
  • 成员函数做友元

1. 全局函数做友元

friend	void goodGay(Building &building);
//建筑物类
class Building
{
	//goodGay全局函数是 Building 友元,可以访问Building中私有成员
	friend	void goodGay(Building &building);

public:
	Building()
	{
		m_SittingRoom = "客厅";
		m_BedRoom = "卧室";
	}
public:
	string m_SittingRoom;
private:
	string m_BedRoom;
};

//全局函数
void goodGay(Building &building)
{
	cout << "goodGay的全局函数正在访问:" << building.m_SittingRoom << endl;
	
	cout << "goodGay的全局函数正在访问:" << building.m_BedRoom << endl;
}
void test4051()
{
	Building building;
	goodGay(building);
}
int main()
{
	test4051();
	system("pause");
	return 0;
}

只需要将函数声明写在类的最上,在声明前加friend即可。

2. 类做友元

friend class GoodGay;
class Building1;
class GoodGay
{
public:
	GoodGay();
	void visit();//参观函数 访问Building 中的属性
	Building1 * building;
};

class Building1
{
	//添加GoodGay类是本类的友元
    //告诉编译器GoodGay类是友元,可以访问到Buliding1中的私有成员
	friend class GoodGay;
public:
	Building1();

public:
	string m_SittingRoom;
private:
	string m_BedRoom;
};

//类外写成员函数
Building1::Building1() 
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}

GoodGay::GoodGay()
{
	//创建一个建筑物的对象
	building = new Building1;	//在堆区创建一个对象,返回一个指针
}

void GoodGay::visit()
{
	cout << "GoodGay类正在访问:" << building->m_SittingRoom << endl;
	//添加GoodGay为友元后,下行代码不报错
	cout << "GoodGay类正在访问:" << building->m_BedRoom << endl;
}

void test4061()
{
	GoodGay gg;
	gg.visit();
}

int main()
{
	test4061();
	system("pause");
	return 0;
}

3. 成员函数做友元

friend void  GoodGay1::visit();
class Building2;
class GoodGay1
{
public:
	GoodGay1();

	void visit();	//让visit函数可以访问Building2中私有成员
	void visit2();	//让visit2函数不可访问Building2中私有成员
	Building2 * building;
};
class Building2
{
	//告诉编译器 GoodGay1类下的成员函数visit作为本类的友元
	//可以访问私有成员
	friend void  GoodGay1::visit();
public:
	Building2();
public:
	string m_SittingRoom;
private:
	string m_BedRoom;
};

//类外写成员函数
Building2::Building2()
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}

GoodGay1::GoodGay1()
{
	building = new Building2;
}

void GoodGay1::visit()
{
	cout << "visit函数正在访问:" << building->m_SittingRoom << endl;
	cout << "visit函数正在访问:" << building->m_BedRoom << endl;
}

void GoodGay1::visit2()
{
	cout << "visit2函数正在访问:" << building->m_SittingRoom << endl;
}

void test4071()
{
	GoodGay1 gg;
	gg.visit();
	gg.visit2();
}
int main()
{
	test4071();
	system("pause");
	return 0;
}

12.5 运算符重载

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

1. 加法运算符重载

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

class Person1
{
public:
	int m_A;
	int m_B;
	//1、通过成员函数重载+号
	Person1 operator+(Person1 &p)
	{
		Person1 temp;
		temp.m_A = p.m_A + this->m_A;
		temp.m_B = p.m_B + this->m_B;
		return temp;
	}
};

//2、通过全局函数重载+号
Person1 operator+(Person1 &p1, Person1 &p2)
{
	Person1 temp;
	temp.m_A = p1.m_A + p2.m_A;
	temp.m_B = p1.m_B + p2.m_B;
	return temp;
}
//函数重载的版本
Person1 operator+(Person1 &p, int num)
{
	Person1 temp;
	temp.m_A = p.m_A + num;
	temp.m_B = p.m_B + num;
	return temp;
}

void test01()
{
	Person1 p1;
	p1.m_A = 10;
	p1.m_B = 10;
	Person1 p2;
	p2.m_A = 10;
	p2.m_B = 10;
	//成员函数重载本质调用:
	//Person1 p3 = p1.operator+(p2);

	//全局函数重载的本质调用:
	//Person1 p3 = operator+(p1, p2);

	Person1 p3 = p1 + p2;

	//运算符重载,也可以发生函数重载
	Person1 p4 = p1 + 10;

	cout << "p3.m_A=" << p3.m_A << endl;
	cout << "p3.m_B=" << p3.m_B << endl;

	cout << "p4.m_A=" << p4.m_A << endl;
	cout << "p4.m_B=" << p4.m_B << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结:

  • 对于内置的数据类型的表达式的运算符是不可以改变的
  • 不要滥用运算符重载

2. 左移运算符重载(<<)

作用:可以输出自定义数据类型,实现cout对象就可以输出对象的所有属性

class Person2
{
    //friend 设置友元访问私有属性
	friend ostream & operator<< (ostream &cout, Person2 &p);
public:
	Person2(int a, int b)
	{
		m_A = a;
		m_B = b;
	}
private:
	//利用成员函数重载左移运算符 p.operator<<(cout) 简化版本:p<<cout
	//所以不会利用成员函数重载左移运算符,因为无法实现cout在左侧
	//void operator<<(cout)
	//{
	//}
	int m_A;
	int m_B;
};

//只能用全局函数来重载左移运算符
//右击cout转到定义,查询其数据类型为ostream
//ostream &cout 本质上是起别名,所以ostream &out也能正常运行
ostream & operator<< (ostream &cout, Person2 &p)	//本质 operator<<(cout,p) 简化版本就是cout<<p
{
	cout << "m_A = " << p.m_A << "    m_B= " << p.m_B;
	return cout;
}

void test02()
{
	Person2 p(10, 10);
	//p.m_A = 10;
	//p.m_B = 10;

	//cout << p.m_A << endl;
	//cout << p.m_B << endl;

	//return cout后就可是实现无限追加输出
	cout << p << "hello" << endl;
}
int main()
{
	test02();
	system("pause");
	return 0;
}

3. 递增运算符重载

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

class MyInt
{
	friend ostream & operator<<(ostream & const, MyInt myint);
	
public:
	MyInt()
	{
		m_Num = 0;
	}

	//利用成员函数重载前置++运算符
	//返回& 是为了一直对一个数据进行递增操作
	MyInt & operator++()
	{
		//先自增
		m_Num++;
		//再将自身进行返回
		return *this;
	}

	//利用成员函数重载后置++运算符
	//void operator++(int) int表示占位参数,可以用来区分前置和后置递增
	//因为temp是局部变量,函数调用完即释放,所以不能使用引用传递,要用值传递
	MyInt operator++(int)
	{
		//先记录当前结果
		MyInt temp = *this;
		//后递增
		m_Num++;
		//对记录结果返回
		return temp;
	}
private:
	int m_Num;
};

//重载<<运算符
ostream & operator<<(ostream & const, MyInt myint)
{
	cout << myint.m_Num;
	return cout;
}
void test01()
{
	MyInt myint;

	cout << ++myint << endl;
}

void test02()
{
	MyInt myint;
	cout << myint++<< endl;	//0
	cout << myint<< endl;	//1
}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}
//递减运算符的重载
class MyInt
{
	friend ostream & operator<<(ostream & const, MyInt myint);

public:
	//构造函数赋初值
	MyInt()
	{
		m_Num = 4;
	}

	//利用成员函数重载前置--运算符
	//返回& 是为了一直对一个数据进行递增操作
	MyInt & operator--()
	{
		//先自减
		m_Num--;
		//再将自身进行返回
		return *this;
	}

	//利用成员函数重载后置--运算符
	//void operator--(int) int表示占位参数,可以用来区分前置和后置递增
	//因为temp是局部变量,函数调用完即释放,所以不能使用引用传递,要用值传递
	MyInt operator--(int)
	{
		//先记录当前结果
		MyInt temp = *this;
		//后递增
		m_Num--;
		//对记录结果返回
		return temp;
	}
private:
	int m_Num;
};

//重载<<运算符
ostream & operator<<(ostream & const, MyInt myint)
{
	cout << myint.m_Num;
	return cout;
}
void test01()
{
	MyInt myint;

	cout << --myint << endl;
}

void test02()
{
	MyInt myint;
	cout << myint-- << endl;	//4
	cout << myint << endl;	//3
}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

4. 赋值运算符重载

C++编译器至少给一个类添加了四个函数

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

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

浅拷贝:简单的赋值拷贝操作,编译器提供的简单赋值操作 eg:m_Height = p.m_Height

深拷贝:用new在堆区重新申请空间,进行拷贝操作 eg:m_Height = new int(*p.m_Height);

浅拷贝会出现的问题:堆区的内存重复释放。

解决方法:利用深拷贝

class Person
{
public:
	Person(int age)
	{
		m_Age = new int(age);//将传入参数开辟到堆区,并使用m_Age来维护
	}

	//析构,释放堆区数据
	~Person()
	{
		if (m_Age)
		{
			delete m_Age;
			m_Age == NULL;
		}

	}
	//为了解决重复释放堆区数据问题,采用深拷贝,所以重载赋值运算符
	//为了实现多个实例赋值,返回本身
	//避免数据复制,所以采用引用传递
	Person & operator=(Person & p)
	{
		//编译器提供的是浅拷贝	m_Age = p.m_Age;

		//应该先判断自身堆区是否有数据存在,如果有,要先释放干净再深拷贝
		if (m_Age)
		{
			delete m_Age;
			m_Age = NULL;
		}
		//*p.m_Age解引用,new int(*p.m_Age)返回解引用后的地址
		//深拷贝
		m_Age = new int(*p.m_Age);	
		//为实现连等,返回其本身
		return *this;
	}
	int * m_Age;
};

void test01()
{
	Person p1(18);
	Person p2(20);
	Person p3(30);

	p3 = p2 = p1;	//赋值操作

	cout << "p1 age =" << *p1.m_Age << endl;
	cout << "p2 age =" << *p2.m_Age << endl;
	cout << "p3 age =" << *p3.m_Age << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

5. 关系运算符重载

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

示例

class Person
{
public:

	Person(string name,int age)
	{
		m_Name = name;
		m_Age = age;
	}
	//重载关系运算符==
	bool operator==(Person & p)
	{
		if ((this->m_Name == p.m_Name) && (this->m_Age == p.m_Age))
			return true;
		else
			return false;
	}
	//重载关系运算符!=
	bool operator!=(Person & p)
	{
		if ((this->m_Name == p.m_Name) && (this->m_Age == p.m_Age))
			return false;
		else
			return true;
	}

	string m_Name;
	int m_Age;
};

void test01()
{
	Person p1("胡图图", 23);
	Person p2("小美", 23);

	//if (p1 == p2)
	//	cout << "p1和p2相等" << endl;
	//else
	//	cout << "p1和p2不相等" << endl;
	if (p1 != p2)
		cout << "p1和p2不相等" << endl;
	else
		cout << "p1和p2相等" << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

6. 函数调用运算符重载

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

示例:

//打印输出的类
class MyPrint
{
public:
	//重载函数调用运算符
	void operator()(string test)
	{
		cout << test << endl;
	}
};

void MyPrint02(string test)
{
	cout << test << endl;
}
void test01()
{
	MyPrint myPrint;
	//对象使用重载后的()
	//仿函数
	myPrint("How are you?");
	//函数调用
	MyPrint02("I am fine,thank you.");
}

//仿函数非常灵活,没有固定的写法
class MyAdd
{
public:
	int operator()(int num1,int num2)
	{
		return num1 + num2;
	}
};

void test02()
{
	MyAdd myadd;
	int ret = myadd(100, 100);
	cout << ret << endl;

	//匿名对象 MyAdd()
	//MyAdd()(100, 100)又进行了重载,匿名函数对象
	cout << MyAdd()(100, 100) << endl;	//200
}

int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

注意身体,肾结石断学5天(其实是懒

12.6 继承

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

有些类和类之间存在特殊的关系,比如:下级别的成员除了拥有上一级的共性,还有自己的特性

1. 基础语法

普通实现:

class 子类: 继承方式 父类
  • 子类也称为派生类
  • 父类也称为基类
//普通实现页面
//class Java
//{
//public:
//	void header()
//	{
//		cout << "首页、公开课、登录、注册、...(公共头部)" << endl;
//	}
//	void footer()
//	{
//		cout << "帮助中心...(公共底部)" << endl;
//	}
//	void left()
//	{
//		cout << "Java\Python\C++....(公共分类列表)" << endl;
//	}
//	void content()
//	{
//		cout << "Java学科视频" << endl;
//	}
//};

//继承实现页面
//继承的好处:减少重复的代码
class BasePage
{
	public:
	void header()
	{
		cout << "首页、公开课、登录、注册、...(公共头部)" << endl;
	}
	void footer()
	{
		cout << "帮助中心...(公共底部)" << endl;
	}
	void left()
	{
		cout << "Java\Python\C++....(公共分类列表)" << endl;
	}
};

//Java页面
class Java :public BasePage
{
public:
	void content()
	{
		cout << "Java学科视频" << endl;
	}
};

//Python页面
class Python :public BasePage
{
public:
	void content()
	{
		cout << "Python学科视频" << endl;
	}
};
void test()
{
	cout << "Java下载视频的页面如下:" << endl;
	Java ja;
	ja.header();
	ja.footer();
	ja.left();
	ja.content();
	cout << "---------------------" << endl;
	cout << "Python下载视频的页面如下:" << endl;
	Python py;
	py.header();
	py.footer();
	py.left();
	py.content();
}
int main()
{
	test();
	system("pause");
	return 0;
}

2. 继承方式

继承方式一共有三种

  • 公共继承
  • 保护继承
  • 私有继承
class Base1
{
public:
	int m_A;
protected:
	int m_B;
private:
	int m_C;
};
//公共继承
class Son1 :public Base1
{
public:
	void func()
	{
		m_A = 10;	//父类中的公共权限成员到子类中任然是公共权限
		m_B = 20;	//父类的保护权限成员到子列中任然是保护权限
		//m_C = 20;	//父类中的私有权限成员 子类访问不到
	}
};
//保护继承
class Son2 :protected Base1
{
public:
	void func()
	{
		m_A = 10;	//父类中公共成员,到子类中变成保护权限
		m_B = 10;	//父类中保护成员,到子类中还是保护权限
		//m_C = 10;		//父类中的私有成员,子类访问不到
	}
};

//私有继承
class Son3 :private Base1
{
public:
	void func()
	{
		m_A = 20;	//父类中公共成员,到子类中变成私有成员
		m_B = 20;	//父类中保护成员,到子类中变为私有成员
		//m_C = 20;		//父类中的私有成员,子类访问不到	
	}
};
void test01()
{
	Son1 s1;
	s1.m_A = 100;
	//s1.m_B = 100;	//保护权限 类外不可被访问
}
void test02()
{
	Son2 s2;
	//s2.m_A = 100;	//在Son2中 m_A变为保护权限,因此类外无法访问
}
void test03()
{
	Son3 s3;
	//s3.m_A = 100;	//在Son2中 m_A变为私有成员,因此类外无法访问
}

3. 继承中的对象模型

Q:从父类继承过来的成员,哪些属于子类对象中

示例:

class Base
{
public:
	int m_A;
protected:
	int m_B;
private:
	int m_C;
};

class Son :public Base
{
public:
	int m_D;
};

void test01()
{
	//在父类中所有非静态成员属性都会被子类继承下去
	//父类中的私有成员属性,是被编译器隐藏了,因此访问不到,但是确实被继承下去了
	cout << "sizeof son" << sizeof(Son) << endl;	//16
}

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

4. 继承中构造和析构顺序

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

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

A:先构造父类再构造子类,析构的顺序与构造的顺序相反

class Base
{
public:
	Base()
	{
		cout << "Base的构造函数!" << endl;
	}

	~Base()
	{
		cout << "Base的析构函数!" << endl;
	}
};

class Son :public Base
{
public:
	Son()
	{
		cout << "Son的构造函数!" << endl;
	}

	~Son()
	{
		cout << "Son的析构函数" << endl;
	}
};

void test01()
{
	//Base b;
	//创建子类对象
	/*
	Base的构造函数!
	Son的构造函数!
	Son的析构函数
	Base的析构函数!
	*/
	//继承中的构造和析构顺序如下:
	//先构造父类再构造子类,析构的顺序与构造的顺序相反
	Son s;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

5. 继承同名函数处理方式

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

A:

  • 访问子类同名成员:直接访问即可
  • 访问父类同名成员:需要加作用域

注意:

  • 如果通过子类对象访问到父类中同名成员属性/函数,需要加作用域
  • 如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏掉父类中所有同名成员函数
    如果想访问到父类中被隐藏的同名成员函数,需要加作用域

示例:

class Base
{
public:
	Base()
	{
		m_A = 100;
	}
	void func()
	{
		cout << "Base-func的调用" << endl;
	}
	void func(int a)
	{
		cout << "Base-func(int a)的调用" << endl;
	}
	int m_A;
};
class Son :public Base
{
public:
	Son()
	{
		m_A = 200;
	}
	void func()
	{
		cout << "Son-func的调用" << endl;
	}
	int m_A;
};

//同名成员属性的处理方式
void test01()
{
	Son s;
	cout << "Son 下的 m_A=" << s.m_A << endl;	//m_A=200
	//如果通过子类对象访问到父类中同名成员属性,需要加作用域
	cout << "Base 下的 m_A=" << s.Base::m_A << endl;	//Base 下的 m_A=100
}
//同名成员函数处理方式
void test02()
{
	Son s;
	s.func();	//Son-func的调用
	//如果通过子类对象访问到父类中同名成员函数,需要加作用域
	s.Base::func();	//Base-func的调用
	//s.func(100) error
	//因为如果子类中出现和父类同名的成员函数
	//子类的同名成员会隐藏掉父类中所有同名成员函数
	//如果想访问到父类中被隐藏的同名成员函数,需要加作用域
	s.Base::func(100);	//Base-func(int a)的调用
}

int main()
{
	test02();
	//test01();
	system("pause");
	return 0;
}

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

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

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

  • 访问子类同名成员,直接访问即可
  • 访问父类同名成员,需要加作用域

注意:

  • 同名静态成员处理和非静态处理一样,只不过有两种访问的方式(通过对象和通过类名)
  • 如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏掉父类中所有同名成员函数
    如果想访问到父类中被隐藏的同名成员函数,需要加作用域

示例:

class Base
{
public:
	static int m_A;
	static void func()
	{
		cout << "Base-static func()" << endl;
	}
	static void func(int a)
	{
		cout << "Base-static func(int a)" << endl;
	}
};
//类内声明类外初始化
int Base::m_A = 100;

class Son :public Base
{
public:
	static int m_A;
	static void func()
	{
		cout << "Son-static func()" << endl;
	}
};
int Son::m_A = 200;
//同名静态成员属性
void test01()
{
	//1、通过对象来访问数据
	Son s;
	cout << "Son m_A=" << s.m_A << endl;	//Son m_A=200
	cout << "Base m_A=" << s.Base::m_A << endl;	//Base m_A = 100
	//2、通过类名来访问数据
	cout << "通过类名来访问数据:" << endl;
	cout << "Son m_A=" << Son::m_A << endl;		//Son m_A=200
	//第一个::代表通过类名的方式来访问,第二个::代表访问父类作用域下
	cout << "Base m_A=" << Son::Base::m_A << endl;	//Base m_A=100
}
//同名静态成员函数
void test02()
{
	//1、通过对象访问
	Son s;
	s.func(); //Son-static func()
	s.Base::func();	//Base-static func()
	//2、通过类名访问
	Son::func();	//Son-static func()
	Son::Base::func();	//Base-static func()
	//子列中出现和父类同名静态成员函数,也会隐藏父类中所有成员函数
	//如果想访问父类中被隐藏的父类成员函数,需要加作用域
	Son::Base::func(100);	//Base-static func(int a)
}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

7. 多继承语法

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

语法:

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

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

实际开发中不建议使用

示例:

class Base1
{
public:
	Base1()
	{
		m_A = 100;
	}
	int m_A;
};

class Base2
{
public:
	Base2()
	{
		m_A = 200;
	}
	int m_A;
};

//子类,需要继承Base1和Base2
class Son :public Base1, public Base2
{
public:
	Son()
	{
		m_C = 300;
		m_D = 400;
	}
	int m_C;
	int m_D;
};
void test01()
{
	Son s;
	cout << "sizeof(Son)=" << sizeof(s) << endl;	//sizeof(Son)=16
	//当父类中出现同名成员,需要加作用域区分
	cout << "Base1 m_A=" << s.Base1::m_A << endl;	//Base1 m_A=100
	cout << "Base2 m_A=" << s.Base2::m_A << endl;	//Base2 m_A = 200
}
int main()
{
	test01();
	system("pause");
	return 0;
}

8. 菱形继承

def:

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

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

多继承可能会引发二义性和数据重复继承,可以通过虚继承解决以上问题

class Animal
{
public:
	int m_Age;
};

//利用虚继承可以解决菱形继承的问题
//在继承前加上关键字virtual 变为虚继承
//Animal 类称为虚基类
class Sheep:virtual public Animal{};

class Tuo:virtual public Animal{};

class SheepTup:virtual public Sheep,virtual public Tuo{};

void test01()
{
	SheepTup st;
	st.Sheep::m_Age = 18;
	st.Tuo::m_Age = 20;
	//当菱形继承,两个父类拥有相同数据,需要加以作用域区分
	cout << "Sheep::m_Age =" << st.Sheep::m_Age << endl;	//Sheep::m_Age =18
	cout << "Tuo::m_Age =" << st.Tuo::m_Age << endl;	//Tuo::m_Age = 20
	//菱形继承导致 SheepTuo的年龄数据有两份,造成了资源浪费
	//可以通过虚继承解决这个问题
	cout << "st.m_Age=" << st.m_Age << endl;	//st.m_Age=20
}
int main()
{
	test01();
	system("pause");
	return 0;
}

12.7 多态

1. 多态的基本概念

多态分为两类

  • 静态多态:函数重载和运算符重载属于静态多态,复用函数名
  • 动态多态:派生类和虚函数实现运行时多态

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

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

案例:

class Animal
{
public:
	//虚函数
	virtual void speak()
	{
		cout << "动物在说话" << endl;
	}
};

class Cat :public Animal
{
public:
	void speak()
	{
		cout << "小猫在说话" << endl;
	}
};

class Dog :public Animal
{
public:
	void speak()
	{
		cout << "小狗在说话" << endl;
	}
};

//地址早绑定
//在编译阶段就确定函数地址
//如果想执行猫说话,那么函数地址就不能早绑定,需要在运行阶段进行绑定,地址晚绑定

//动态多态满足条件
//1、有继承关系
//2、子类要重写父类的虚函数

//动态多态使用
//父类的指针或者引用执行子类对象
void doSpeak(Animal &animal)	//Animal &animal =cat/dog
{
	animal.speak();
}
void test01()
{
	Cat cat;
	doSpeak(cat);	

	Dog dog;
	doSpeak(dog);
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结:

多态满足条件:有继承关系;子类重写父类中的虚函数

多态使用条件:父类指针或引用指向子类对象

重写:函数返回值类型 函数名 参数列表 完全一致称为重写

2. 多态案例 - 计算机类

案例描述:分别利用普通写法和多态技术,设计实现两个操作数进行计算的计算器类

多态的优点:

  • 代码结构清晰
  • 可读性强
  • 利于前期和后期扩展和维护
//普通写法
class Calculator
{
public:
	int getResult(string opt)
	{
		if (opt == "+")
		{
			return m_Num1 + m_Num2;
		}
		else if (opt == "-")
		{
			return m_Num1 - m_Num2;
		}
		else if (opt == "*")
		{
			return m_Num1 * m_Num2;
		}
		//如果想扩展新的功能,需要修改源码
		//在真实的开发中,提倡开闭原则:对扩展进行开放,对修改进行关闭
	}
	int m_Num1;
	int m_Num2;
};
void test01()
{
	//创建计算器类
	Calculator c;
	c.m_Num1 = 10;
	c.m_Num2 = 10;
	cout << c.m_Num1 << "+" << c.m_Num2 << "=" << c.getResult("+") << endl;
	cout << c.m_Num1 << "-" << c.m_Num2 << "=" << c.getResult("-") << endl;
	cout << c.m_Num1 << "*" << c.m_Num2 << "=" << c.getResult("*") << endl;
}
//利用多态实现计算器
//实现计算器基类
//多态使用的好处:组织结构清晰;可读性强;对于前期和后期维护性高

//实现计算机抽象类
class AbstractCalculator
{
public:
	virtual int getResult()
	{
		return 0;
	}
	int m_Num1;
	int m_Num2;
};

//加法计算器类
class AddCalculator :public AbstractCalculator
{
public:
	//重写getResult函数
	int getResult()
	{
		return m_Num1 + m_Num2;
	}
};

//减法计算器类
class SubCalculator :public AbstractCalculator
{
public:
	//重写getResult函数
	int getResult()
	{
		return m_Num1 - m_Num2;
	}
};
//乘法计算器类
class MulCalculator :public AbstractCalculator
{
public:
	//重写getResult函数
	int getResult()
	{
		return m_Num1 * m_Num2;
	}
};
void test02()
{
	//多态使用条件:父类指针或引用指向子类对象

	//加法运算
	AbstractCalculator * abc = new AddCalculator;	//new 一个AddCalculator对象创建在堆区,返回一个指针
	abc->m_Num1 = 10;
	abc->m_Num2 = 20;

	cout << abc->m_Num1 << "+" << abc->m_Num2 << "=" << abc->getResult() << endl;
	delete abc;//创建在堆区要注意销毁数据

	//减法运算,由于上步只是释放堆区的数据,abc的数据类型没有改变
	abc = new SubCalculator;
	abc->m_Num1 = 30;
	abc->m_Num2 = 20;

	cout << abc->m_Num1 << "-" << abc->m_Num2 << "=" << abc->getResult() << endl;
	delete abc;

	//乘法运算
	abc = new MulCalculator;
	abc->m_Num1 = 30;
	abc->m_Num2 = 20;

	cout << abc->m_Num1 << "*" << abc->m_Num2 << "=" << abc->getResult() << endl;
	delete abc;
}
int main()
{
	//test01();
	test02();
	system("pause");
	return 0;
}

3. 纯虚函数和抽象类

在多态中,通常父类中虚函数的实现是毫无意义的,主要是调用子类重写的内容。因此可以将虚函数改为纯虚函数

纯虚函数的语法:

virtual 返回值类型 函数名 {参数列表} =0;

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

抽象类特点:

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

示例:

class Base
{
public:
	//纯虚函数
	//只要有一个纯虚函数,则称为抽象类
	virtual void func() = 0;
};

class Son :public Base
{
public:
	void func()
	{
		cout << "func函数调用" << endl;
	}
};

void test01()
{
	//Base b; error 因为抽象类无法实例化对象
	//new Base; error 抽象类无法实例化对象

	Son s;	//子类必须重写父类中的纯虚函数,否则子类也属于纯虚函数无法实例化对象

	Base * base = new Son;
	base->func();
}
int main()
{
	test01();
	system("pause");
	return 0;
}

4. 多态案例二 - 制作饮品

案例描述:制作饮品的大致流程是:煮水-冲泡- 倒入杯中- 加入辅料

利用多态技术实现本案例,提供抽象制作饮品积累,提供子类制作咖啡和茶叶

示例:

class AbstractDrinking
{
public:
	//煮水纯虚函数
	virtual void Boil() = 0;
	//冲泡纯虚函数
	virtual void Brew() = 0;
	//倒入杯中
	virtual void PourInCup() = 0;
	//放入辅料
	virtual void PutSt() = 0;
	//制作饮品
	void makeDranking()
	{
		Boil();
		Brew();
		PourInCup();
		PutSt();
	}
};

//制作咖啡
class Coffee :public AbstractDrinking
{
public:
	//煮水
	void Boil()
	{
		cout << "煮水" << endl;
	}
	//冲泡
	void Brew()
	{
		cout << "冲泡咖啡" << endl;
	}
	//倒入杯中
	void PourInCup()
	{
		cout << "倒入咖啡杯中" << endl;
	}
	//放入辅料
	virtual void PutSt()
	{
		cout << "加入牛奶和方糖" << endl;
	}
};

//制作茶叶
class Tea :public AbstractDrinking
{
public:
	//煮水
	void Boil()
	{
		cout << "煮山泉水" << endl;
	}
	//冲泡
	void Brew()
	{
		cout << "冲泡茶叶" << endl;
	}
	//倒入杯中
	void PourInCup()
	{
		cout << "倒入茶杯中" << endl;
	}
	//放入辅料
	virtual void PutSt()
	{
		cout << "加入蜂蜜" << endl;
	}
};

//制作函数
void doWork(AbstractDrinking * abs)
{
	abs->makeDranking();
	delete abs; //释放堆区数据
}
void test01()
{
	//制作咖啡
	doWork(new Coffee);

	cout << "------------" << endl;
	//制作茶水
	doWork(new Tea);
}
int main()
{
	test01();
	system("pause");
	return 0;
}

5. 虚析构和纯虚析构函数

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

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

虚析构和纯虚析构共性

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

区别

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

虚析构语法:

virtual ~类名(){}

纯虚构语法:

virtual ~类名()=0;
类名::~类名(){}

示例

class Animal
{
public:
	Animal()
	{
		cout << "Animal 构造函数调用" << endl;
	}
	//利用虚析构可以解决父类指针 释放子类对象时不干净的问题
	//virtual ~Animal()
	//{
	//	cout << "Animal 析构函数调用" << endl;
	//}
	
	//纯虚析构 需要声明也需要实现,类内声明,类外实现
	//有了纯虚析构之后,这个类也属于抽象类,无法实例化对象
	virtual ~Animal() = 0;

	//纯虚函数
	virtual void speak() = 0;
};

Animal::~Animal()
{
	cout << "Animal 纯虚析构函数调用" << endl;
}

class Cat :public Animal
{
public:
	Cat(string name)
	{
		cout << "Cat 的构造函数调用" << endl;
		m_Name = new string(name);
	}
	void speak()
	{
		cout << *m_Name << "小猫在说话" << endl;
	}
	~Cat()
	{
		if (m_Name != NULL)
		{
			cout << "Cat 的析构函数调用" << endl;
			delete m_Name;
			m_Name = NULL;
		}
	}
	string * m_Name;	//属性开辟到堆区
};

void test01()
{
	Animal* animal = new Cat("Tom");
	animal->speak();
	//父类指针在析构的时候,不会调用子类中析构函数,导致子类如果有堆区数据,会出现内存泄露情况
	delete animal;	//Tom小猫在说话
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结:

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

6. 多态案例三 - 电脑组装

案例描述:

电脑主要组成部件为CPU,显卡,内存条。将每个零件封装成抽象类,并且提供不同的厂商生产不同的零件,创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口,测试时组装三台不同的电脑进行工作

示例:

//抽象CPU类
class CPU
{
public:
	//抽象计算函数
	virtual void calculrtor() = 0;
};

//抽象显卡类
class VideoCard
{
public:
	//抽象显示函数
	virtual void display() = 0;
};

//抽象存储类
class Memory
{
public:
	//抽象存储函数
	virtual void storage() = 0;
};

class Computer
{
public:
	Computer(CPU * cpu, VideoCard * vc, Memory * m)
	{
		m_cpu = cpu;
		m_vc = vc;
		m_m = m;
	}

	//提供工作函数
	void doWork()
	{
		//调用具体的接口让零件工作起来
		m_cpu->calculrtor();
		m_vc->display();
		m_m->storage();
	}

//提供析构函数,释放三个电脑零件
	~Computer()
	{
		//释放cpu零件
		if (m_cpu != NULL)
		{
			delete m_cpu;
			m_cpu = NULL;
		}
		//释放显卡零件
		if (m_vc != NULL)
		{
			delete m_vc;
			m_vc = NULL;
		}
		//释放内存条零件
		if (m_m != NULL)
		{
			delete m_m;
			m_m = NULL;
		}
	}
private:
	CPU * m_cpu;	//CPU零件
	VideoCard * m_vc;	//显卡零件指针
	Memory * m_m;	//内存条零件指针

};

//具体厂商
//Intel 
class IntelCPU :public CPU
{
public:
	void calculrtor()
	{
		cout << "这是Intel的CPU开始计算了" << endl;
	}
};
class IntelVideoCard :public VideoCard
{
public:
	void display()
	{
		cout << "这是Intel的显卡开始显示了" << endl;
	}
};

class IntelMemory :public Memory
{
public:
	void storage()
	{
		cout << "这是Intel的内存条开始存储了" << endl;
	}
};

//lenovo厂商
class LenovoCPU :public CPU
{
public:
	void calculrtor()
	{
		cout << "这是Lenovo的CPU开始计算了" << endl;
	}
};
class LenovoVideoCard :public VideoCard
{
public:
	void display()
	{
		cout << "这是Lenovo的显卡开始显示了" << endl;
	}
};

class LenovoMemory :public Memory
{
public:
	void storage()
	{
		cout << "这是Lenovo的内存条开始存储了" << endl;
	}
};

void test01()
{
	cout << "第一台电脑工作" << endl;
	cout << "-----------------------------------" << endl;
	//第一台电脑组装
	//创建第一台电脑零件
	CPU * intelCpu = new IntelCPU;	//用父类指针指向子类对象
	VideoCard * intelCard = new IntelVideoCard;
	Memory * intelMem = new IntelMemory;

	//创建第一台电脑
	Computer * computer1 = new Computer(intelCpu, intelCard, intelMem);
	computer1->doWork();
	delete computer1;

	cout << endl;
	cout << "第二台电脑工作" << endl;
	cout << "-----------------------------------" << endl;
	//第二台电脑组装
	零件
	//CPU * lenovoCpu = new LenovoCPU;
	//VideoCard * lenovoCard = new LenovoVideoCard;
	//Memory * lenovoMem = new LenovoMemory;

	//创建电脑
	Computer * computer2 = new Computer(new LenovoCPU, new LenovoVideoCard, new LenovoMemory);
	computer2->doWork();
	delete computer2;

	cout << endl;
	cout << "第三台电脑工作" << endl;
	cout << "-----------------------------------" << endl;
	//第三台电脑组装
	//创建电脑
	Computer * computer3 = new Computer(new IntelCPU, new LenovoVideoCard, new LenovoMemory);
	computer3->doWork();
	delete computer3;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

13 文件操作

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

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

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

文件类型可以分为两种

  • 文本文件 - 文件以文本的ASCII码形式存储在计算机中
  • 二进制文件 - 文件以文本的二进制形式存储在计算机中,用户一般不能直接读取到

操作文件的三大类

  • ofstream 写操作
  • ifstream 读操作
  • fstream 读写操作

13.1 文本文件

1. 写文件

写文件步骤如下:

1、包含头文件

#include<fstream>

2、创建流对象

ofstream ofs;

3、打开文件

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

4、写数据

ofs<<"写入的数据";

5、关闭文件

ofs.close();

文件打开方式

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

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

例如:用二进制方式写文件

ios::binary||ios::out

示例:

#include<iostream>
#include<string>
#include<fstream>	//头文件的包含
using namespace std;

void test01()
{
	//创建流对象
	ofstream ofs;
	//指定打开方式
	//不指定文件路径,会默认创建在当前项目所在文件路径下
	ofs.open("test.txt", ios::out);
	//写内容
	ofs << "胡图图" << endl;
	ofs << "胡英俊" << endl;
	ofs << "张晓丽" << endl;
	ofs << "小美" << endl;
	//关闭文件
	ofs.close();
}

int main()
{
	test01();
	system("pause");
	return 0;
}

2. 读文件

读文件和写文件步骤相似,但是读取方式相对比较多

读取文件步骤如下:

1、包含头文件

#include<fstream>

2、创建流对象

ifstream ifs;

3、打开文件并判断文件是否打开成功

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

4、读数据

四种方式读取

5、关闭文件

ifs.close();

示例

void test01()
{
	ifstream ifs;

	//打开文件,并且判断是否打开成功
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}
	//读数据
	//1、第一种
	char buf[1024] = { 0 };
	while (ifs >> buf)
	{
		cout << buf << endl;
	}

	//第二种
	char buf[1024] = { 0 };
	while (ifs.getline(buf, sizeof(buf)))
	{
		cout << buf << endl;
	}

	//第三种
	string buf;
	while (getline(ifs, buf))
	{
		cout << buf << endl;
	}

	//第四种
	char c;
	//EOF end of file没有读到文件尾就一直读
	while ((c = ifs.get()) != EOF)
	{
		cout << c;
	}
	//关闭文件
	ifs.close();
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结

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

13.2 二进制文件

以二进制的方式对文件进行读写操作

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

1. 写文件

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

函数原型

//字符型指针buffer指向内存中的一段存储空间,len是读写的字节数
ostream& write(const char * buffer,int len);

示例

#include<iostream>
#include<string>
#include<fstream>	//包含头文件
using namespace std;

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

void test01()
{
	//创建流对象
	ofstream ofs("person.txt", ios::out | ios::binary);

	//打开文件
	//ofs.open("person.txt", ios::out | ios::binary);

	//写文件
	Person p = { "胡图图", 23 };
	ofs.write((const char *)&p, sizeof(Person));

	//关闭文件
	ofs.close();
}
int main()
{
	test01();
	system("pause");
	return 0;
}

总结:文件输出流对象可以通过write函数,以二进制方式写数据

2. 读文件

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

函数原型

//字符指针buffer指向内存中的一段存储空间,len是读写的字节数
istream & read(char * buffer,int len);

示例

#include <iostream>
using namespace std;
#include <string>
#include <fstream>

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

void test()
{
	//创建流对象
	ifstream ifs;
	//打开文件 并判断是否打开成功
	ifs.open("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}
	//读数据
	Person p;
	ifs.read((char *)&p, sizeof(Person));
	cout << "姓名:" << p.m_Name << "年龄:" << p.m_Age << endl;
	ifs.close();
	
}
int main()
{
	test();
	system("pause");
	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值