c++结构体再学习

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。}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值