内容来源于:黑马
集成开发环境:CLion
先前学习完了C++第1章的内容:
C++ 入门速通-第1章【黑马】-CSDN博客
下面继续学习第4章:
结构体的基本应用:




结构体成员默认值:
结构体数组:

简单案例:
cpp
// struct 结构体
#include "iostream"
using namespace std;
/*
* 声明语法:
* struct 结构体类型名
* {
* 成员类型 成员名;
* ...
* ...
* }
*
* */
// 特点:一个结构体类型,可以包含多个成员,每个成员都有自己的类型和名称。可以做到一批不同的数据类型,使用同一个变量名。
int main()
{
struct Student // 一种新的数据类型,是我们自己定义的
{
string name;
int age;
string gender;
string major_code = "3210xx";
};
// 小细节:结构体变量的声明,可以在前面带上struct关键字,也可以不带 【建议带上】
struct Student stu1;
// Student stu; // 结构体变量
// stu1.name = "张三";
// stu1.age = 20;
// stu1.gender = "男";
stu1 = {"李四", 18, "男"};
// 结构体变量是一个整体的包装,无法直接cout输出; 需要访问每一个成员进行输出
// 访问语法: 结构体变量名.成员名
cout << stu1.name << endl;
cout << stu1.age << endl;
cout << stu1.gender << endl;
cout << "----------------------------" << endl;
struct Student stu2 = {"王五", 19, "女", "321023"};
cout << stu2.name << endl;
cout << stu2.age << endl;
cout << stu2.gender << endl;
cout << stu2.major_code << endl;
cout << "----------------------------" << endl;
// 结构体数组
struct Student arr[3] = {
{"赵六", 20, "男"},
{"钱七", 21, "女"},
{"孙八", 22, "男"}
};
for (int i = 0; i < 3; ++i) {
cout << arr[i].name << endl;
cout << arr[i].age << endl;
cout << arr[i].gender << endl;
cout << endl;
}
return 0;
}
结构体指针:


结构体指针数组:

简单案例:

函数的概念:



基础函数语法:

简单案例:
cpp
// function 函数
#include "iostream"
using namespace std;
// 编写一个函数:接收2个int数字传入,返回两者中最大的数值
int max(int a, int b)
{
return a > b ? a : b;
}
int main()
{
// 函数的使用在main函数内编写
int max_num = max(1, 2);
cout << "max_num = " << max_num << endl;
cout << "----------------------------" << endl;
return 0;
}


无返回值函数和 void 类型:

空参函数:

函数嵌套调用:

参数的值传递和地址传递:



函数传入数组:

引用的基本概念:




引用传参:



返回指针的函数以及局部变量的生命周期:



static 关键字:

简单案例:
cpp
// static 关键字
#include "iostream"
using namespace std;
/*
* static 是一个关键字,可以修饰变量和函数
* - 修饰变量,可以让被修饰的变量的生命周期一直持续到程序结束,不受函数结束的影响
*
* */
int * add(int a, int b)
{
static int sum;
sum = a + b;
return ∑
}
int main()
{
int * result = add(1, 2);
cout << *result << endl;
return 0;
}
函数返回数组:




函数默认值:


补充:



C++一套通关系列课程在线笔记:https://www.yuque.com/bigdata-caoyu/newcp
参考: