C++ 结构体(Struct)是一种用户自定义的数据类型,它允许将不同类型的数据组合在一起。结构体的定义和使用在 C++ 编程中非常常见,因此了解结构体的相关知识对于 C++ 程序员来说非常重要。本文将详细介绍结构体的定义、初始化、访问、嵌套结构体、结构体与函数、结构体指针等方面的内容,帮助读者更好地理解和掌握结构体的使用。
一、结构体定义
结构体的定义使用关键字 struct,后面跟着结构体的名称和一对花括号,花括号内是结构体的成员变量。例如:
```cpp
struct Student {
std::string name;
int age;
float score;
};
```
这里定义了一个名为 Student 的结构体,包含三个成员变量:name(姓名),age(年龄)和 score(分数)。
二、结构体初始化
结构体的初始化可以通过以下几种方式进行:
1. 定义时直接初始化:
```cpp
struct Student {
std::string name = "张三";
int age = 18;
float score = 90.5;
};
```
2. 声明后初始化:
```cpp
struct Student {
std::string name;
int age;
float score;
};
Student stu1 = {"李四", 20, 95.0};
```
3. 使用构造函数初始化:
```cpp
struct Student {
std::string name;
int age;
float score;
Student(const std::string& n, int a, float s) : name(n), age(a), score(s) {}
};
Student stu2("王五", 22, 88.0);
```
三、结构体访问
结构体的成员变量可以通过 . 运算符进行访问。例如:
```cpp
#include <iostream>
#include <string>
using namespace std;
struct Student {
std::string name;
int age;
float score;
};
int main() {
Student stu = {"张三", 18, 90.5};
cout << "姓名:" << stu.name << endl;
cout << "年龄:" << stu.age << endl;
cout << "分数:" << stu.score << endl;
return 0;
}
```
四、嵌套结构体
结构体可以嵌套在其他结构体内,形成多层嵌套的结构体。例如:
```cpp
struct Address {
std::string city;
std::string street;
};
struct Student {
std::string name;
int age;
float score;
Address address; // 嵌套 Address 结构体作为成员变量
};
```
五、结构体与函数
结构体可以作为函数的参数和返回值。例如:
```cpp
#include <iostream>
#include <string>
using namespace std;
struct Student {
std::string name;
int age;
float score;
};
void printStudentInfo(const Student& stu) { // 结构体作为函数参数和返回值示例1:传递引用参数,避免拷贝开销;返回值类型为 const 引用,防止修改原对象信息。注意:如果需要修改原对象信息,应传递非 const 引用参数。同时,函数内部也可以直接访问结构体成员变量。例如:stu.name, stu.age, stu.score。}