一、前言
内置类型 int/string 只能存储单一数据,结构体可以把多个不同类型数据打包为一个自定义类型,用于存储学生、商品、用户等多属性实体,是面向对象类的前置基础。
二、结构体定义与创建对象
基础定义语法
cpp
运行
struct Student
{
// 成员变量
string name;
int age;
double score;
}; // 分号不可省略
三种创建结构体对象方式:
cpp
运行
// 方式1:定义后单独创建
Student s1;
// 方式2:创建同时初始化
Student s2 = {"小明", 18, 92.5};
// 方式3:定义结构体时直接创建对象
struct Book
{
string title;
} b1, b2;
三、结构体成员访问
普通结构体对象:
.点运算符访问成员
cpp
运行
Student s = {"小红",17,88};
cout << s.name << " " << s.age;
s.score = 95; // 修改成员数据
结构体指针:
->箭头运算符访问成员
cpp
运行
Student s = {"小李",18,76};
Student *p = &s;
cout << p->name << endl;
p->score = 80;
四、结构体做函数参数
1. 值传递(拷贝完整结构体,数据量大性能差)
cpp
运行
void printStu(Student s)
{
cout << s.name << s.score;
}
2. 引用传递(推荐,无拷贝,高效)
cpp
运行
void setScore(Student &s, double sc)
{
s.score = sc;
}
3. const 常量引用(只读展示数据最优方案)
cpp
运行
void showInfo(const Student &s)
{
cout << s.name << " " << s.age << " " << s.score;
}
五、结构体数组(批量存储多条实体)
存储全班多名学生数据,结合循环遍历:
cpp
运行
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
double score;
};
int main()
{
Student classArr[3] = {
{"张三",18,90},
{"李四",17,85},
{"王五",18,78}
};
for(int i = 0; i < 3; i++)
{
cout << classArr[i].name << " " << classArr[i].score << endl;
}
return 0;
}
六、结构体嵌套(复杂多层数据)
结构体内部包含另一个结构体,适用于地址、订单等多层信息:
cpp
运行
struct Address
{
string city;
string street;
};
struct User
{
string username;
int id;
Address addr; // 嵌套结构体成员
};
int main()
{
User u = {"admin", 1001, {"杭州","滨江大道"}};
cout << u.addr.city;
return 0;
}
七、新手易错点
结构体定义末尾遗漏分号
;,编译报错结构体指针误用
.,普通对象误用->结构体值传递拷贝大量数据,大数据场景造成性能损耗
八、综合实战:学生信息录入与平均分统计
cpp
运行
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
double score;
};
// 计算平均分
double calcAvg(Student arr[], int len)
{
double sum = 0;
for(int i = 0; i < len; i++)
{
sum += arr[i].score;
}
return sum / len;
}
int main()
{
Student stu[4];
for(int i = 0; i < 4; i++)
{
cout << "输入第" << i+1 << "位学生姓名、分数:";
cin >> stu[i].name >> stu[i].score;
}
double avg = calcAvg(stu,4);
cout << "班级平均分:" << avg;
return 0;
}
九、下期预告
下一篇:C++ 面向对象入门:类与对象、封装基础