📚 结构体概述
什么是结构体?
结构体(struct)是一种用户自定义的数据类型,它可以将不同类型的数据组合在一起,形成一个整体。结构体非常适合表示具有多个属性的实体。
- ✅ 数据聚合:将相关数据组织在一起
- ✅ 类型安全:编译器检查类型匹配
- ✅ 代码清晰:提高程序可读性
- ✅ 易于维护:集中管理相关数据
- ✅ 广泛应用:学生信息、坐标点、日期等
💡 结构体 vs 类:
• struct:默认成员是public,主要用于数据存储
• class:默认成员是private,支持封装和方法
• 在C++中,struct可以包含函数,但通常用于简单数据集合
结构体的定义
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int age;
double score;
string major;
};
int main() {
Student stu1;
stu1.name = "张三";
stu1.age = 18;
stu1.score = 92.5;
stu1.major = "计算机科学";
cout << "姓名:" << stu1.name << endl;
cout << "年龄:" << stu1.age << endl;
cout << "成绩:" << stu1.score << endl;
cout << "专业:" << stu1.major << endl;
return 0;
}
结构体初始化
#include <iostream>
#include <string>
using namespace std;
struct Point {
double x;
double y;
};
int main() {
Point p1;
p1.x = 3.0;
p1.y = 4.0;
Point p2 = {1.0, 2.0};
Point p3{5.0, 6.0};
Point p4 = {.x = 7.0, .y = 8.0};
cout << "p1: (" << p1.x << ", " << p1.y << ")" << endl;
cout << "p2: (" << p2.x << ", " << p2.y << ")" << endl;
cout << "p3: (" << p3.x << ", " << p3.y << ")" << endl;
return 0;
}
⚙️ 结构体数组
结构体数组的定义和使用
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int age;
double score;
};
int main() {
Student students[3];
students[0] = {"张三", 18, 92.5};
students[1] = {"李四", 19, 88.0};
students[2] = {"王五", 20, 95.0};
for (int i = 0; i < 3; i++) {
cout << "学生" << (i+1) << ":";
cout << students[i].name << ", ";
cout << students[i].age << "岁, ";
cout << "成绩:" << students[i].score << endl;
}
double total = 0;
for (int i = 0; i < 3; i++) {
total += students[i].score;
}
cout << "平均分:" << total / 3 << endl;
return 0;
}
动态结构体数组
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Product {
string name;
double price;
int quantity;
};
int main() {
vector<Product> products;
products.push_back({"苹果", 5.5, 100});
products.push_back({"香蕉", 3.2, 150});
products.push_back({"橙子", 4.8, 80});
cout << "=== 商品清单 ===" << endl;
for (const auto& product : products) {
cout << product.name << ": ";
cout << "¥" << product.price << " × ";
cout << product.quantity << "个" << endl;
}
double totalValue = 0;
for (const auto& product : products) {
totalValue += product.price * product.quantity;
}
cout << "总价值:¥" << totalValue << endl;
return 0;
}
🎮 互动实验:结构体数组演示
输入学生数量,自动生成结构体数组代码
输入数量后点击按钮...
🛠️ 结构体嵌套
嵌套结构体的定义
#include <iostream>
#include <string>
using namespace std;
struct Date {
int year;
int month;
int day;
};
struct Student {
string name;
int age;
Date birthDate;
double score;
};
int main() {
Student stu;
stu.name = "张三";
stu.age = 18;
stu.birthDate.year = 2006;
stu.birthDate.month = 5;
stu.birthDate.day = 15;
stu.score = 92.5;
cout << "姓名:" << stu.name << endl;
cout << "生日:" << stu.birthDate.year << "-";
cout << stu.birthDate.month << "-";
cout << stu.birthDate.day << endl;
return 0;
}
复杂嵌套示例:地址信息
#include <iostream>
#include <string>
using namespace std;
struct Address {
string province;
string city;
string district;
string street;
};
struct Contact {
string phone;
string email;
};
struct Person {
string name;
int age;
Address address;
Contact contact;
};
void printPerson(const Person& p) {
cout << "=== 个人信息 ===" << endl;
cout << "姓名:" << p.name << endl;
cout << "年龄:" << p.age << endl;
cout << "地址:" << p.address.province
<< p.address.city << p.address.district
<< p.address.street << endl;
cout << "电话:" << p.contact.phone << endl;
cout << "邮箱:" << p.contact.email << endl;
}
int main() {
Person person;
person.name = "李四";
person.age = 25;
person.address = {"广东省", "深圳市", "南山区", "科技路1号"};
person.contact = {"13800138000", "lisi@example.com"};
printPerson(person);
return 0;
}
结构体作为函数参数
#include <iostream>
#include <string>
using namespace std;
struct Rectangle {
double width;
double height;
};
double calculateArea(Rectangle rect) {
return rect.width * rect.height;
}
void scaleRectangle(Rectangle& rect, double factor) {
rect.width *= factor;
rect.height *= factor;
}
void printRectangle(const Rectangle& rect) {
cout << "矩形:" << rect.width << "x" << rect.height << endl;
cout << "面积:" << calculateArea(rect) << endl;
}
int main() {
Rectangle rect = {5.0, 3.0};
printRectangle(rect);
scaleRectangle(rect, 2.0);
printRectangle(rect);
return 0;
}
🚀 结构体与类的区别
主要区别对比
struct MyStruct {
int x;
void show() {
cout << x << endl;
}
};
class MyClass {
int x;
public:
void setX(int val) { x = val; }
int getX() { return x; }
void show() {
cout << x << endl;
}
};
int main() {
MyStruct s;
s.x = 10;
s.show();
MyClass c;
c.setX(10);
c.show();
return 0;
}
💡 选择建议:
• 使用struct:简单的数据集合,不需要封装
• 使用class:需要封装、继承、多态等OOP特性
• 实际开发:大多数情况使用class更规范
实际应用:学生管理系统
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct Student {
string name;
int id;
double score;
};
bool compareByScore(const Student& a, const Student& b) {
return a.score > b.score;
}
int findStudent(const vector<Student>& students, int id) {
for (size_t i = 0; i < students.size(); i++) {
if (students[i].id == id) {
return i;
}
}
return -1;
}
int main() {
vector<Student> students = {
{"张三", 1001, 92.5},
{"李四", 1002, 88.0},
{"王五", 1003, 95.0}
};
sort(students.begin(), students.end(), compareByScore);
cout << "=== 成绩排名 ===" << endl;
for (size_t i = 0; i < students.size(); i++) {
cout << (i+1) << ". ";
cout << students[i].name << " (ID:";
cout << students[i].id << ") - ";
cout << students[i].score << "分" << endl;
}
int index = findStudent(students, 1002);
if (index != -1) {
cout << "\n找到学生:" << students[index].name << endl;
}
return 0;
}
📝 实战练习
📝 理解测试
以下代码的输出是什么?
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
void modify(Point p) {
p.x = 100;
p.y = 200;
}
int main() {
Point pt = {1, 2};
modify(pt);
cout << pt.x << "," << pt.y << endl;
return 0;
}
选择答案查看解析...
💻 综合挑战
题目:设计一个Book(图书)结构体系统:
1. 定义Book结构体:书名、作者、价格、ISBN
2. 创建图书数组(至少3本书)
3. 实现功能:查找最贵的书、计算平均价格、按价格排序
4. 输出所有图书信息和统计结果
点击"生成代码框架"查看提示...