C++基础入门 --- 【学习指南】

173 阅读23分钟

C++基础入门

1.初识C++

1.1 第一个C++程序

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World!" << endl;
    system("pause");
    return 0;
}

1.2 注释

作用:在所编写的代码中添加解释和说明,方便其他程序员阅读代码。

两种格式:

1.单行注释://描述信息//

通常放在一行代码上方,对该行代码进行注释说明。

#include <iostream>
using namespace std;

int main()
{
    //cout << "Hello World!" << endl;
    system("pause");
    return 0;
}

2.多行注释:/* 描述信息*/

通常放在一端代码的上方,对该段代码进行整体注释说明。

#include <iostream>
using namespace std;

/*int main()
{
    cout << "Hello World!" << endl;
    system("pause");
    return 0;
}*/

补充:编译器在编译代码时,会省略掉注释的内容。

1.3 变量

作用:给一段指定的内存空间进行命名,以便进行相应的操作。

语法结构:数据类型 变量名 = 初始值;

#include <iostream>
using namespace std;

int main()
{
    char ch = 'a';
    int a = 10;
    float f = 3.14f;

    cout << ch << endl;
    cout << a << endl;
    cout << f << endl;

    system("pause");
    return 0;
}

1.4 常量

作用:用于记录程序中不可被修改的数据。

两种方式:

1.#define 宏常量

语法结构:#define 常量名 常量值

2.const 修饰的变量

语法结构:#const 数据类型 常量名 = 常量值;

#include <iostream>
using namespace std;

//宏定义
#define M 10

int main()
{
    //const修饰的变量
    const int a = 10;
    M = 20; //报错
    a = 30; //报错
    system("pause");
    return 0;
}

1.5 关键字

定义:预定义的保留标识符,对编译器有特殊意义。

asmdoifreturntypedef
autodoubleinlineshorttypeid
booldynamic_castintsignedtypename
breakelselongsizeofunion
caseenummutablestaticunsigned
catchexplicitnamespacestatic_castusing
charexportnewstructvirtual
classexternoperatorswitchviod
constfalseprivatetemplatevolatile
const_castfloatprotectedthiswchar_t
continueforpublicthrowwhile
defaultfriendregistertrue
deletegotoreinterpret_casttry

补充:在定义变量或常量时名称不可与C++的关键字相同,否则会有歧义。

1.6 标识符命名规则

  1. 第一个字符必须是字母(不分大小写)或者下划线(__)。

  2. 标识符只能由字母(不分大小写)、数字、下划线(__)组成。

  3. 标识符中的大小写字母有区别。

  4. 标识符不能是编译系统预定定义的、有特殊用途的关键字同名。

2.数据类型

说明:在创建一个变量或常量时,必须要指定相对应的数据类型,不然无法给变量或常量分配内存。不同的数据类型,开辟的内存空间大小也不同。

数据类型占用空间取值范围
char1个字节[-128,127]或[0, 255]
unsigned char1个字节[0, 255]
signed char1个字节[-128,127]
int4个字节[-2147483648 ,2147483647]
unsigned int4个字节[0 , 4294967295]
signed int4个字节[-2147483648 , 2147483647]
short int2个字节[-32768 , 32767]
unsigned short int2个字节[0 , 65,535]
signed short int2个字节[-32768 , 32767]
long int8个字节[-9,223,372,036,854,775,808 , 9,223,372,036,854,775,807]
signed long int8个字节[-9,223,372,036,854,775,808 , 9,223,372,036,854,775,807]
unsigned long int8个字节[0 , 18,446,744,073,709,551,615]
float4个字节单精度型占4个字节内存空间,7位有效数字
double8个字节双精度型占8 个字节内存空间,15~16位有效数字
long long16个字节[ -9,223,372,036,854,775,807 , 9,223,372,036,854,775,807]
long double16个字节长双精度型 16 个字节内存空间,18-19位有效数字。
wchar_t2个字节或4个字节1 个宽字符

2.1 整型

作用:整型变量表示类型为整型的数据。

数据类型占用空间取值范围
short(短整型)2个字节[-32768 , 32767]
int(整型)4个字节[-2147483648 ,2147483647]
long(长整型)4字节(32位或8个字节(64位)[-2147483648 ,2147483647]
long long(长长整型)8个字节[ -9,223,372,036,854,775,807 , 9,223,372,036,854,775,807]

2.2 sizeof关键字

作用:可以计算数据类型所占内存空间大小。

语法结构:sizeof(数据类型 / 变量)

#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    cout << sizeof(a) << endl;

    cout << sizeof(char) << endl;
    cout << sizeof(short) << endl;
    cout << sizeof(int) << endl;
    cout << sizeof(float) << endl;
    cout << sizeof(double) << endl;
    cout << sizeof(long) << endl;
    cout << sizeof(long long) << endl;
    system("pause");
    return 0;
}

2.3 浮点型(实型)

作用:可表示有小数的数据。

两种类型:

  1. 单精度类型float

  2. 双精度类型double

区别:

数据类型占用空间有效数字范围
float4个字节7位有效数字
double8个字节15~16位有效数字
#include <iostream>
using namespace std;

int main()
{
    float f = 3.14f;
    double d = 2.13;

    cout << f << endl;
    cout << d << endl;
    cout << sizeof(f) << endl;
    cout << sizeof(d) << endl;
    system("pause");
    return 0;
}

2.4 字符型

作用:用于显示单个字符。

语法结构:char 变量名 = '初始值';

  • 定义字符型变量时,要使用单引号括起来,不可使用双引号

  • 字符型常量存储时不是把字符本身放入内存存储,而是将对应的ASCII编码存放入存储单元。

#include <iostream>
using namespace std;

int main()
{
    char ch = 'a';
    ch = "b"; //报错
    system("pause");
    return 0;
}

ASCII码表:

大致由两部分组成:

  1. ASCII非打印控制字符:0-31分配给了控制字符,用于控制打印机等一些外围设备。

  2. ASCII打印字符:32-126分配给了可在键盘找到的字符。

ASCII值控制字符ASCII值字符ASCII值字符ASCII值字符
0NUT32(space)64@96
1SOH33!65A97a
2STX34"66B98b
3ETX35#67C99c
4EOT36$68D100d
5ENQ37%69E101e
6ACK38&70F102f
7BEL39,71G103g
8BS40(72H104h
9HT41)73I105i
10LF42*74J106j
11VT43+75K107k
12FF44,76L108l
13CR45-77M109m
14SO46'78N110n
15SI47/79O111o
16DLE48080P112p
17DC149181Q113q
18DC250282R114r
19DC351383S115s
20DC452484T116t
21NAK53585U117u
22SYN54686V118v
23TB55787W119w
24CAN56888X120x
25EM57989Y121y
26SUB58:90Z122z
27ESC59;91[123{
28FS60<92/124
29GS61=93]125}
30RS6294126'
31US63?95__127DEL

2.5 转义字符

作用:表示不能显示出来的ASCII值。

转义字符含义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进制转义字符,h范围A~F3位十六进制
#include <iostream>
using namespace std;

int main()
{
    cout << "\\" << endl;
    cout << "\thello\tworld" << endl;
    cout << "\n" << endl;
    system("pause");
    return 0;
}

2.6 字符串型

作用:用来表示一串字符。

两种形式:

1.C风格

语法结构:char 变量名[] = "字符串值";

2.C++风格

语法结构:string 变量名 = “字符串值”;

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

int main()
{
    char ch1[] = "abcd";
    string ch2 = "efg";
    system("pause");
    return 0;
}

补充:

1.C风格的字符串在变量名后需要加[]。

2.C++风格的字符串,使用时需要引入头文件#include。

2.7 布尔类型 bool

作用:表示真或假的值。占用空间大小一个字节。

bool类型只有两种值:

  1. true -- 真(本质是1)

  2. false -- 假(本质是0)

#include <iostream>
using namespace std;

int main()
{
    bool n = true;
    cout << n << endl;

    n = false;
    cout << n << endl;

    cout << sizeof(bool) << endl;
    system("pause");
    return 0;
}

2.8 数据的输入

作用:从键盘获取输入数据。

关键字:cin

语法结构:cin >> 变量

#include <iostream>
using namespace std;

int main()
{
    int n = 0;
    cout << "请输入一个整型数据:" << endl;
    cin >> n;
    cout << n << endl;
    system("pause");
    return 0;
}

3.运算符

作用:用于代码的运算。

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

3.1 算术运算符

作用:处理四则运算。

运算符术语举例结果
+正号+11
-负号-11
+1+12
-1-10
*2*510
/10/25
%取模(取余)10%31
++前置递增a=2;b=++a;a=3;b=3;
++后置递增a=2;b=a++;a=3;b=2;
--前置递减a=2;b=--a;a=1;b=1;
--后置递减a=2;b=a--;a=1;b=2;
#include <iostream>
using namespace std;

int main()
{
    int num1 = 10;
    int num2 = 5;

    cout << num1 + num2 << endl;
    cout << num1 - num2 << endl;
    cout << num1 * num2 << endl;
    cout << num1 / num2 << endl;

    int num3 = 2;
    int num4 = 0;
    cout << cout3 / cout4 << endl; //报错,除数不可为0
    system("pause");
    return 0;
}

3.2 赋值运算符

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

运算符术语举例结果
=赋值a=1;a=1;
+=加等于a=1;a+=2;a=3;
-=减等于a=1;a-=1;a=0;
*=乘等于a=1;a*=3;a=3;
/=除等于a=10;a/=2;a=5;
%=模等于a=10;a%=3;a=1;
#include <iostream>
using namespace std;

int main()
{
    int a = 10;

    a = 20;
    cout << "a=" << a << endl;

    a += 10;
    cout << "a=" << a << endl;

    a -= 20;
    cout << "a=" << a << endl;

    a /= 2;
    cout << "a=" << a << endl;

    a *= 2;
    cout << "a=" << a << endl;

    a %= 3;
    cout << "a=" << a << endl;
    system("pause");
    return 0;
}

3.3 比较运算符

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

运算符术语举例结果
==相等于1 == 20
!=不等于1 != 21
<小于1  <  21
大于1  >  20
<=小于等于1 <= 21
>=大于等于1 >= 20
#include <iostream>
using namespace std;

int main()
{
    int a = 1;
    int b = 2;

    cout << (a == b) << endl;
    cout << (a != b) << endl;
    cout << (a < b) << endl;
    cout << (a > b) << endl;
    cout << (a <= b) << endl;
    cout << (a >= b) << endl;

    system("pause");
    return 0;
}

3.4 逻辑运算符

作用:根据表达式的值返回真值或假值。

运算符术语举例结果
!aa为假,结果为真;a为真,结果为假
&&a&&b全1出1,有0出0(1:真  0:假)
|a|
#include <iostream>
using namespace std;

int main()
{
    int a = 1;
    int b = 2;

    cout << !a << endl;
    cout << !!a << endl;
    cout << (a && b) << endl;
    cout << (a || b) << endl;
    system("pause");
    return 0;
}

4.程序运行结构

  • 顺序结构:程序按顺序执行,不发生跳转

  • 选择结构:判断条件是否满足,选择性区执行相应的代码

  • 循环结构:判断条件是否满足,循环多次执行某段代码

4.1 选择结构

4.1.1 if语句

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

三种形式

  • 单行格式if语句

  • 多行格式if语句

  • 多条件格式if语句

#include <iostream>
using namespace std;

//单行if语句
int main()
{
    int score = 0;
    cout << "请输入你的成绩:" << endl;
    cin >> score;

    if (score >= 60)
    {
        cout << "及格!" << endl;
    }

    system("pause");
    return 0;
}
//多行if语句
int main()
{
    int score = 0;
    cout << "请输入你的成绩:" << endl;
    cin >> score;

    if (score >= 80)
    {
        cout << "良好!" << endl;
    }
    else if (score >= 60)
    {
        cout << "及格!" << endl;
    }
    else
    {
        cout << "不及格!" << endl;
    }

    system("pause");
    return 0;
}
//多条件if语句
int main()
{
    int score = 0;
    cout << "请输入你的成绩:" << endl;
    cin >> score;

    if (score >= 80)
    {
        if (score >= 90)
            cout << "优秀!" << endl;
        else
            cout << "良好!" << endl;
    }
    else if (score >= 60)
    {
        cout << "及格!" << endl;
    }
    else
    {
        cout << "不及格!" << endl;
    }

    system("pause");
    return 0;
}
4.1.2 三目运算符

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

语法结构:表达式1 ? 表达式2:表达式3

说明

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

如果表达式1的值为假,执行表达式3,并返回表达式3执行后的结果。

#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    int b = 2;
    int c = 0;

    c = a > b ? a : b;
    cout << c << endl;

    (a > b ? a : b) = 5; //在C++中三目运算符返回的是变量,可以继续进行赋值操作。
    cout << a << endl;
    system("pause");
    return 0;
}
4.1.3 switch语句

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

语法结构

switch(表达式)
{
    case 常量表达式1: 语句1;break;
    case 常量表达式2: 语句2;break;      '
    case 常量表达式n: 语句n;break;
    ......
    default: 语句n+1;
}
#include <iostream>
using namespace std;

int main()
{
    int day = 0;
    cin >> day;

    switch (day)
    {
    case 1:
        cout << "星期一" << endl;
        break;

    case 2:
        cout << "星期二" << endl;
        break;
    case 3:
        cout << "星期三" << endl;
        break;
    case 4:
        cout << "星期四" << endl;
        break;
    case 5:
        cout << "星期五" << endl;
        break;
    case 6:
        cout << "星期六" << endl;
        break;
    case 7:
        cout << "星期天" << endl;
        break;
    default:
        cout << "输入错误!" << endl;
        break;
    }
    system("pause");
    return 0;
}

补充:case中如果没有break,程序将会一直向下执行。

4.2 循环结构

4.2.1 while循环语句

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

语法结构:while(循环条件) {循环语句}

说明:只要循环条件的结果为真,就执行循环语句。

#include <iostream>
using namespace std;

int main()
{
    int num = 1;
    while (num <= 10)
    {
        cout << num << endl;
        num++;
    }
    system("pause");
    return 0;
}
4.2.2 do..while循环语句

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

语法结构:do{循环语句} while(循环条件);

#include <iostream>
using namespace std;

int main()
{
    int num = 1;
    do
    {
        cout << num << endl;
        num++;
    } while (num <= 10);
    system("pause");
    return 0;
}

补充:do..while与while的区别就是会先执行一次循环语句,再判断循环条件。

4.2.3 for循环语句

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

语法结构:for(表达式1;表达式2;表达式3){循环体语句;}

表达式1:

表达式1为初始化部分,用来进行循环变量赋值。

表达式2:

表达式2为条件判断部分,用来控制循环条件。

表达式3:

表达式3为调整部分,用来控制循环变量递增或递减。

#include <iostream>
using namespace std;

int main()
{
    int i = 0;
    for (i = 1; i <= 10; i++)
    {
        cout << i << endl;
    }
    system("pause");
    return 0;
}

4.2.4 嵌套循环

作用:在循环体中再嵌套一层循环,解决实际问题。

例如:打印一个10 x 10的矩形,就需要用到嵌套循环。

#include <iostream>
using namespace std;

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

4.3 跳转语句

4.3.1 break语句

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

常用

  • 在switch条件语句中,终止case跳出switch

  • 在循环语句中,跳出当前循环语句

  • 在嵌套循环中,跳出最近的内存循环语句

//switch条件语句
#include <iostream>
using namespace std;

int main()
{
    int day = 0;
    cin >> day;
    switch (day)
    {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        cout << "工作日" << endl;
        break;
    case 6:
    case 7:
        cout << "休息日" << endl;
        break;
    default:
        cout << "error" << endl;
        break;
    }
    system("pause");
    return 0;
}
//循环语句
#include <iostream>
using namespace std;

int main()
{
    for (int i = 1; i <= 10; i++)
    {
        if (i == 5)
            break;
        cout << i << endl;
    }
    system("pause");
    return 0;
}
//嵌套循环
#include <iostream>
using namespace std;

int main()
{
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            if (j == 5)
                break;
            cout << "* ";
        }
        cout << endl;
    }
    system("pause");
    return 0;
}
4.3.2 continue语句

作用:在循环语句中,跳过本次循环中尚未执行的部分,执行下一次的循环。

#include <iostream>
using namespace std;

int main()
{
    for (int i = 1; i <= 10; i++)
    {
        if (i == 5)
            continue;
        cout << i << endl;
    }
    system("pause");
    return 0;
}
4.3.3 goto语句

作用:如果标记的名称存在,程序执行到goto语句时,将会跳转到标记的位置执行。

语法结构:goto 标记;

#include <iostream>
using namespace std;

int main()
{
    for (int i = 1; i <= 10; i++)
    {
        if (i == 5)
            goto end;
        cout << i << endl;
    }
end:
    cout << "结束" << endl;
    system("pause");
    return 0;
}

5.数组

定义:数组就是一组存放相同类型的数据元素的集合,由连续的内存位置组成。

5.1 一维数组

5.1.1 一维数组的定义方式

三种方式

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

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

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

#include <iostream>
using namespace std;

int main()
{
    int arr1[5];
    int arr2[5] = { 10,20,30,40,50 };
    int arr3[] = { 60,70,80,90,100 };

    //赋值
    arr1[0] = 5;
    arr1[1] = 15;
    arr1[2] = 25;
    arr1[3] = 35;
    arr1[4] = 45;

    //输出
    cout << arr1[0] << endl;
    cout << arr1[1] << endl;
    cout << arr1[2] << endl;
    cout << arr1[3] << endl;
    cout << arr1[4] << endl;

    //输出 
    for (int i = 0; i < 5; i++)
    {
        cout << arr2[i] << endl;
    }

    system("pause");
    return 0;
}
5.1.2 一维数组数组名

作用:统计整个数组在内存中的长度,获取数组在内存中的首地址。

#include <iostream>
using namespace std;

int main()
{
    int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };

    cout << "数组在内存中的大小为:" << sizeof(arr) << endl;
    cout << "数组中每个元素在内存所占空间大小为:" << sizeof(arr[0]) << endl;
    cout << "数组的元素个数为:" << sizeof(arr) / sizeof arr[0] << endl;

    cout << "数组首元素地址为:" << arr << endl;
    cout << "数组第一个元素地址为:" << &arr[0] << endl;
    cout << "数组第二个元素地址为:" << &arr[1] << endl;

    arr = 10; //报错,数组名是常量不可进行赋值。
    system("pause");
    return 0;
}
5.1.3 冒号排序

作用:对数组内元素进行排序。

#include <iostream>
using namespace std;

int main()
{
    int arr[] = { 3,5,8,2,7,9,6,4 };
    int len = sizeof(arr) / sizeof(arr[0]);
    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;
            }
        }
    }

    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

5.2 二维数组

定义:就是一个有行和列的矩阵,每一行代表一个数组。

5.2.1 二维数组的定义方式

4种方式

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

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

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

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

#include <iostream>
using namespace std;

int main()
{
    int arr1[3][3];
    int arr2[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    int arr3[3][3] = { 10,11,12,13,14,15,16,17,18 };
    int arr4[][3] = { 19,20,21,22,23,24,25,26,27 };

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cout << arr2[i][j] << " ";
        }
        cout << endl;
    }
    system("pause");
    return 0;
}
5.2.2 二维数组的数组名

作用:查看二维数组所占内存空间大小,获取二维数组首地址。

#include <iostream>
using namespace std;

int main()
{
    int arr[3][3] = { 1,2,3,4,5,6,7,8,9 };

    cout << "数组在内存中的大小为:" << sizeof(arr) << endl;
    cout << "数组中每个元素在内存所占空间大小为:" << sizeof(arr[0][0]) << endl;
    cout << "数组的元素个数为:" << sizeof(arr) / sizeof arr[0][0] << endl;

    cout << "数组首元素地址为:" << arr << endl;
    cout << "数组第一个元素地址为:" << &arr[0][0] << endl;
    cout << "数组第二个元素地址为:" << &arr[0][1] << endl;

    system("pause");
    return 0;
}

6.函数

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

6.1 函数的定义

语法结构:

返回值类型 函数名(参数列表)
{
    函数体语句

    return表达式
}
#include <iostream>
using namespace std;

int add(int num1, int num2)
{
    return num1 + num2;
}

int main()
{
    int num1 = 10;
    int num2 = 20;
    int ret = add(num1, num2);
    cout << ret << endl;
    system("pause");
    return 0;
}

6.2 函数的调用

作用:使用定义好的函数。

语法结构:函数名(参数)

#include <iostream>
using namespace std;

int Sub(int num1, int num2)   //这边的num1,num2为形参
{
    return num1 - num2;
}

int main()
{
    int n1 = 10;
    int n2 = 20;
    //调用Sub函数
    int ret = Sub(n1, n2); //这边的n1,n2为实参
    cout << ret << endl;
    system("pause");
    return 0;
}

6.3 值传递

作用:函数调用时将数值传入形参。

#include <iostream>
using namespace std;

void swap(int num1, int num2)
{
    int temp = num1;
    num1 = num2;
    num2 = temp;
    cout << num1 << endl;
    cout << num2 << endl;
}
int main()
{
    int x = 10;
    int y = 20;
    swap(x, y);
    cout << x << endl;
    cout << y << endl;
    system("pause");
    return 0;
}

补充:形参发生,不会影响实参。

6.4 函数的常见格式

常见的函数格式有4种:

  • 无参无返

  • 有参无返

  • 无参有返

  • 有参有返

#include <iostream>
using namespace std;

//无参无返
void test()
{
    cout << "hello world" << endl;
}

//有参无返
void test2(int a)
{
    cout << "this is test" << endl;
}

//无参有返
int test3()
{
    return 1;
}

//有参有返
int test4(int a)
{
    a += 2;
    return a;
}

6.5 函数声明

作用:告诉便编译器函数名称以及如何调用函数。

#include <iostream>
using namespace std;

//声明
int max(int x, int  y);
int max(int x, int  y);
int max(int x, int  y);

//定义
int max(int x, int  y)
{
    return x > y ? x : y;
}
int main()
{
    int a = 10;
    int b = 20; 
    int c = max(a, b);
    cout << c << endl;
    system("pause");
    return 0;
}

补充:函数声明可多次,但定义只可一次。

6.6 函数的分文件编写

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

一般有4个步骤:

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

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

  3. 头文件写函数的声明

  4. 源文件写函数的定义

//main.cpp
#include "swap.h"

int main()
{
    int a = 10;
    int b = 20;
    swap(a, b);
    system("pause");
    return 0;
}
//swap.h
#include <iostream>
using namespace std;

void swap(int x, int y);
//swap.cpp
#include "swap.h"

void swap(int x, int y)
{
    int temp = x;
    x = y;
    y = temp;

    cout << x << endl;
    cout << y << endl;
}

7.指针

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

7.1 指针变量的定义和使用

语法结构: 数据类型 * 变量名;

#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    int* p = &a;
    cout << "a的地址为:" << &a << endl;
    cout << "指针p的地址为:" << p << endl;

    *p = 20;
    cout << "a的值为:" << a << endl;
    cout << "指针p的值为:" << *p << endl;
    system("pause");
    return 0;
}eturn 0;
}

7.2 指针占内存空间大小

大小:在32位操作系统下占4个字节,64位操作系统下占8个字节。

#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    int* p = &a;
    cout << sizeof(p) << endl;
    cout << sizeof(char*) << endl;
    cout << sizeof(float *) << endl;
    cout << sizeof(double *) << endl;
    //都是4个字节
    system("pause");
    return 0;
}

7.3 空指针

定义:指针变量指向内存编号为0的空间。

作用:初始化指针变量。

#include <iostream>
using namespace std;

int main()
{
    int* p = NULL;

    *p = 100;  //报错,内存编号0-255系统占用,不许用户进行访问
    cout << *p << endl;
    system("pause");
    return 0;
}


补充:空指针指向的内存不可访问。

7.4 野指针

定义:指针变量指向非法的内存空间。

#include <iostream>
using namespace std;

int main()
{
    int* p = (int*)0x1234;
    cout << *p << endl;
    system("pause");
    return 0;
}

7.5 const修饰指针

三种形式:

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

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

  3. 修饰指针与常量

#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    int b = 20;
    //const修饰的是指针,指针所指向的地址的内容不可改,指针指向的地址可以改
    const int* p1 = &a; 
    *p1 = 20;  //报错
    p1 = &b;

    //const修饰的是常量,指针所指向的地址的内容可改,指针指向的地址不可改
    int* const p2 = &a;
    *p2 = 20;  
    p2 = &b;   //报错

    //const修饰的是常量与指针,指针所指向的地址的内容不可改,指针指向的地址不可改
    const int* const p3 = &a;
    *p3 = 20;  //报错
    p3 = &b;   //报错

    system("pause");
    return 0;
}

7.6 指针和数组

作用:用指针访问数组元素。

#include <iostream>
using namespace std;

int main()
{
    int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
    int len = sizeof(arr) / sizeof(arr[0]);
    int* p = arr;
    cout << "数组arr的第一个元素为:" << arr[0] << endl;
    cout << "指针p访问的第一个元素为:" << *p << endl;

    for (int i = 0; i < len; i++)
    {
        cout << *(p + i) << endl; //使用指针遍历数组
    }
    system("pause");
    return 0;
}

7.7 指针和函数

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

#include <iostream>
using namespace std;

void swap(int* num1, int* num2)
{
    int temp = *num1;
    *num1 = *num2;
    *num2 = temp;
}

int main()
{
    int a = 10;
    int b = 20;
    cout << "before:" << endl;
    cout << a << endl;
    cout << b << endl;
    swap(&a, &b);
    cout << "after:" << endl;
    cout << a << endl;
    cout << b << endl;
    system("pause");
    return 0;
}

8.结构体

定义:一系列有相同类型或不同类型的数据构成的数据集合。

8.1 结构体的使用

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

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

  1. struct 结构体名 变量名

  2. struct 结构体名 变量名 = {成员1, 成员2, ...成员n};

  3. {}变量名;

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

struct Student
{
    int id;
    string name;
    int age;
}stu1;

int main()
{
    struct Student stu2;
    struct Student stu3 = { 123456,"小明",20 };
    stu2.id = 123457;
    stu2.name = "小红";
    stu2.age = 18;
    cout << "学号:" << stu2.id << " " << "姓名:" << stu2.name << " " << "年龄:" << stu2.age << endl;
    system("pause");
    return 0;
}

8.2 结构体数组

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

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

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

struct Student
{
    int id;
    string name;
    int age;
};

int main()
{
    struct Student stu[3] = { {123456,"A",18},{123457,"B",20},{123458,"C",19} };
    stu[1].age = 22;
    stu[1].id = 123459;
    stu[1].name = "D";
    for (int i = 0; i < 3; i++)
    {
        cout << "学号:" << stu[i].id << " " << "姓名" << stu[i].name << " " << "年龄:" << stu[i].age << endl;
    }
    system("pause");
    return 0;
}

8.3 结构体指针

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

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

struct Student
{
    int id;
    string name;
    int age;
};

int main()
{
    struct Student stu = { 123456,"小明",20 };
    struct Student* p = &stu;
    cout << "学号:" << p->id << " " << "姓名:" << p->name << " " << "年龄:" << p->age << endl;
    system("pause");
    return 0;
}

8.4 结构体嵌套结构体

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

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

struct Student
{
    int id;
    string name;
    int age;
};

struct Teacher
{
    string name;
    int age;
    struct Student stu;
};
int main()
{
    struct Teacher teacher = { "E",26,{123456,"A",19} };
    struct Teacher* p = &teacher;
    cout << "老师姓名:" << p->name << " " << "老师年龄:" << p->age << endl;
    cout << "学生学号:" << p->stu.id << " " << "学生姓名:" << p->stu.name << " " << "学生年龄:" << p->stu.age << endl;
    system("pause");
    return 0;
}

8.5 结构体做函数参数

作用:把结构体作为参数向函数传入。

两种传递方式:

  1. 值传递

  2. 地址传递

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

struct Student
{
    int id;
    string name;
    int age;
};

//值传递
void print1(struct Student stu)
{
    cout << "学号:" << stu.id << " " << "姓名" << stu.name << " " << "年龄:" << stu.age << endl;
}

//地址传递
void print2(struct Student* stu)
{
    cout << "学号:" << stu->id << " " << "姓名" << stu->name << " " << "年龄:" << stu->age << endl;
}

int main()
{
    struct Student stu = { 123456,"A",18 };

    print1(stu);
    print2(&stu);

    system("pause");
    return 0;
}

8.6 const修饰结构体变量

作用:防止误操作。

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

struct Student
{
    int id;
    string name;
    int age;
};

void print(const Student* stu)
{
    stu->age = 50; //报错
    cout << "学号:" << stu->id << " " << "姓名" << stu->name << " " << "年龄:" << stu->age << endl;
}

int main()
{
    struct Student stu = { 123456,"A",18 };
    print(&stu);
    system("pause");
    return 0;
}