1. 结构体进阶:从基础到实战
在C++开发中,结构体(struct)是组织相关数据的利器。很多初学者掌握了结构体的基本用法后,往往在实际项目中遇到各种进阶问题。今天我们就来深入探讨结构体的三个核心进阶用法:typedef别名定义、结构体嵌套以及结构体作为函数参数的各种场景。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 用typedef为类型定义别名
2.1 typedef的基本用法
typedef是C++中为已有类型创建新名称的关键字。对于结构体这种复杂类型,typedef可以显著提升代码可读性:
cpp复制struct Student {
int id;
string name;
double score;
};
typedef Student Stu; // 现在Stu等同于struct Student
这样定义后,Stu就完全等同于struct Student,我们可以直接使用Stu来声明变量:
cpp复制Stu s1; // 等同于 Student s1;
注意:typedef只是创建别名,不会创建新类型。编译器在类型检查时仍会视为同一类型。
2.2 typedef的实用场景
-
简化复杂类型声明:
cpp复制typedef struct { int year; int month; int day; } Date; -
提高指针类型可读性:
cpp复制typedef Student* StudentPtr; // 学生指针类型 -
跨平台兼容性:
cpp复制typedef int32_t FixedSizeInt; // 确保固定大小的整数
2.3 typedef vs using (C++11)
C++11引入了using关键字,也能创建类型别名,且语法更直观:
cpp复制using Stu = Student; // 等价于typedef Student Stu;
using的优势在于支持模板别名:
cpp复制template<typename T>
using Vec = std::vector<T>;
3. 结构体嵌套的艺术
3.1 基本嵌套结构
结构体可以包含其他结构体作为成员,这种嵌套能更好地反映现实世界中的层次关系:
cpp复制struct Address {
string city;
string street;
int zipCode;
};
struct Employee {
int id;
string name;
