- C++
C++ 结构体学习笔记教程
- 2025-8-10 14:14:39 @
C++ 结构体学习笔记教程
1. 结构体的基本概念
结构体(struct
)是C++中一种用户自定义的数据类型,用于将不同类型的数据组合在一起,形成一个新的复合数据类型。结构体非常适合表示具有多个相关属性的实体,如学生、点坐标、书籍信息等。
2. 结构体的定义与使用
基本语法
struct 结构体名称 {
数据类型 成员1;
数据类型 成员2;
// ... 更多成员
};
示例:定义一个学生结构体
#include <iostream>
#include <string>
// 定义结构体
struct Student {
std::string name; // 姓名
int age; // 年龄
float score; // 成绩
};
int main() {
// 创建结构体变量
Student stu1;
// 访问和设置成员
stu1.name = "张三";
stu1.age = 18;
stu1.score = 95.5f;
// 输出结构体成员
std::cout << "姓名: " << stu1.name << std::endl;
std::cout << "年龄: " << stu1.age << std::endl;
std::cout << "成绩: " << stu1.score << std::endl;
return 0;
}
3. 结构体的初始化
结构体可以通过多种方式进行初始化:
#include <iostream>
#include <string>
struct Point {
int x;
int y;
};
struct Book {
std::string title;
std::string author;
int pages;
// 构造函数
Book(std::string t, std::string a, int p) {
title = t;
author = a;
pages = p;
}
// 简化的构造函数
Book(std::string t, std::string a) : title(t), author(a), pages(0) {}
};
int main() {
// 1. 先定义后赋值
Point p1;
p1.x = 10;
p1.y = 20;
// 2. 定义时初始化(C风格)
Point p2 = {15, 30};
// 3. 使用构造函数初始化
Book book1("C++ Primer", "Stanley B. Lippman", 1000);
// 4. 使用另一个构造函数
Book book2("The Great Gatsby", "F. Scott Fitzgerald");
std::cout << "p1: (" << p1.x << ", " << p1.y << ")" << std::endl;
std::cout << "p2: (" << p2.x << ", " << p2.y << ")" << std::endl;
std::cout << "Book 1: " << book1.title << " by " << book1.author
<< ", " << book1.pages << " pages" << std::endl;
std::cout << "Book 2: " << book2.title << " by " << book2.author << std::endl;
return 0;
}
4. 结构体中的成员函数
C++结构体可以包含成员函数,这使得结构体不仅能存储数据,还能包含操作这些数据的方法。
#include <iostream>
#include <string>
struct Rectangle {
float length;
float width;
// 计算面积
float area() {
return length * width;
}
// 计算周长
float perimeter() {
return 2 * (length + width);
}
// 设置尺寸
void setDimensions(float l, float w) {
if (l > 0 && w > 0) { // 确保尺寸为正数
length = l;
width = w;
} else {
std::cout << "错误:尺寸必须为正数!" << std::endl;
}
}
// 显示矩形信息
void display() {
std::cout << "矩形: 长 = " << length
<< ", 宽 = " << width << std::endl;
std::cout << "面积: " << area() << std::endl;
std::cout << "周长: " << perimeter() << std::endl;
}
};
int main() {
Rectangle rect;
rect.setDimensions(5.0f, 3.0f);
rect.display();
// 尝试设置无效尺寸
rect.setDimensions(-2.0f, 4.0f);
return 0;
}
5. 结构体数组与指针
结构体可以像基本类型一样创建数组和指针:
#include <iostream>
#include <string>
struct Employee {
std::string name;
int id;
float salary;
void display() {
std::cout << "ID: " << id
<< ", 姓名: " << name
<< ", 工资: " << salary << std::endl;
}
};
int main() {
// 结构体数组
Employee employees[3] = {
{"张三", 1001, 5000.0f},
{"李四", 1002, 6000.0f},
{"王五", 1003, 5500.0f}
};
std::cout << "所有员工信息:" << std::endl;
for (int i = 0; i < 3; i++) {
employees[i].display();
}
// 结构体指针
Employee emp = {"赵六", 1004, 7000.0f};
Employee* empPtr = &emp;
std::cout << "\n通过指针访问:" << std::endl;
// 两种访问方式:-> 和 (*).
empPtr->display();
(*empPtr).display();
// 指向结构体数组的指针
Employee* arrPtr = employees;
std::cout << "\n通过数组指针访问第一个员工:" << std::endl;
arrPtr->display();
return 0;
}
6. 结构体的嵌套
结构体可以嵌套在其他结构体中,形成更复杂的数据结构:
#include <iostream>
#include <string>
// 地址结构体
struct Address {
std::string street;
std::string city;
std::string state;
int zipCode;
void display() {
std::cout << street << ", " << city << ", "
<< state << " " << zipCode << std::endl;
}
};
// 人员结构体,嵌套了Address结构体
struct Person {
std::string name;
int age;
Address address; // 嵌套结构体
void display() {
std::cout << "姓名: " << name << std::endl;
std::cout << "年龄: " << age << std::endl;
std::cout << "地址: ";
address.display();
}
};
int main() {
Person person;
person.name = "张三";
person.age = 30;
person.address.street = "Main Street 123";
person.address.city = "Beijing";
person.address.state = "CN";
person.address.zipCode = 100000;
person.display();
return 0;
}
7. 结构体与函数
结构体可以作为函数参数传递,也可以作为函数返回值:
#include <iostream>
struct Circle {
float radius;
// 常量成员函数,不修改结构体数据
float getArea() const {
return 3.14159f * radius * radius;
}
};
// 结构体作为参数(值传递)
void printCircleArea(Circle c) {
std::cout << "圆的面积: " << c.getArea() << std::endl;
}
// 结构体作为参数(引用传递)
void doubleRadius(Circle& c) {
c.radius *= 2;
}
// 函数返回结构体
Circle createCircle(float radius) {
Circle c;
c.radius = radius;
return c;
}
int main() {
Circle myCircle = createCircle(5.0f);
printCircleArea(myCircle);
doubleRadius(myCircle);
printCircleArea(myCircle);
return 0;
}
8. 结构体与类的区别
在C++中,结构体(struct
)和类(class
)非常相似,主要区别在于:
-
默认访问权限:
- 结构体的成员默认是
public
(公共的) - 类的成员默认是
private
(私有的)
- 结构体的成员默认是
-
继承默认权限:
- 结构体默认是公有继承
- 类默认是私有继承
-
使用习惯:
- 结构体通常用于存储数据(数据结构)
- 类通常用于实现更复杂的面向对象功能
9. 结构体的实际应用示例
下面是一个综合示例,展示结构体在实际编程中的应用:
#include <iostream>
#include <string>
#include <iomanip>
// 定义日期结构体
struct Date {
int day;
int month;
int year;
std::string toString() {
return std::to_string(day) + "/" +
std::to_string(month) + "/" +
std::to_string(year);
}
};
// 定义学生结构体
struct Student {
std::string id;
std::string name;
Date birthDate;
float grades[3]; // 三门课程成绩
// 计算平均成绩
float averageGrade() const {
float sum = 0;
for (int i = 0; i < 3; i++) {
sum += grades[i];
}
return sum / 3;
}
// 显示学生信息
void display() const {
std::cout << "学号: " << id << std::endl;
std::cout << "姓名: " << name << std::endl;
std::cout << "出生日期: " << birthDate.toString() << std::endl;
std::cout << "成绩: ";
for (int i = 0; i < 3; i++) {
std::cout << grades[i] << " ";
}
std::cout << std::endl;
std::cout << "平均成绩: " << std::fixed << std::setprecision(1)
<< averageGrade() << std::endl;
}
};
// 查找平均分最高的学生
Student findTopStudent(Student students[], int count) {
int topIndex = 0;
float highestAvg = students[0].averageGrade();
for (int i = 1; i < count; i++) {
if (students[i].averageGrade() > highestAvg) {
highestAvg = students[i].averageGrade();
topIndex = i;
}
}
return students[topIndex];
}
int main() {
// 初始化学生数组
Student students[3] = {
{
"2023001", "张三", {15, 3, 2005}, {90.5f, 85.0f, 92.5f}
},
{
"2023002", "李四", {20, 5, 2004}, {88.0f, 91.5f, 89.0f}
},
{
"2023003", "王五", {5, 9, 2005}, {95.0f, 87.5f, 90.0f}
}
};
// 显示所有学生信息
std::cout << "===== 所有学生信息 =====" << std::endl;
for (int i = 0; i < 3; i++) {
students[i].display();
std::cout << std::endl;
}
// 查找并显示成绩最好的学生
Student topStudent = findTopStudent(students, 3);
std::cout << "===== 成绩最好的学生 =====" << std::endl;
topStudent.display();
return 0;
}
总结
结构体是C++中非常重要的数据结构,它允许我们将相关的数据组合在一起,形成有意义的数据单元。通过本教程,你应该已经掌握了:
- 结构体的定义和基本使用方法
- 结构体的初始化方式,包括使用构造函数
- 结构体中成员函数的定义和使用
- 结构体数组和指针的操作
- 结构体的嵌套使用
- 结构体与函数的配合使用
- 结构体与类的区别
结构体在实际编程中应用广泛,掌握结构体的使用对于C++编程至关重要。建议多编写代码练习,加深对结构体的理解和应用能力。
0 条评论
目前还没有评论...