C++ 结构体指针 结构体做函数参数

1、结构体指针
作用:通过指针访问结构体中的成员。
利用操作符:可以通过结构光指针访问结构体属性。
示例:

#include <iostream>
using namespace std;

/// <summary>
/// 定义学生结构体
/// </summary>
struct student
{
    
    
    string name;
    int age;
    int score;
};

int main()
{
    
    
    //创建学生结构体变量
    struct student s = {
    
     "张三",18,100 };
    //通过指针指向结构体变量
    student* p = &s;
    //通过指针访问结构体变量中的数据
    cout << "姓名:"<<p->name << "年龄:" << p->age << "成绩:" << p->score << endl;
    system("puase");
}

2、结构体嵌套结构体
作用:结构体中的成员可以使另一个结构体。
例如:每个老师辅导一个学员,一个老师的结构体中,记录一个学生的结构体。
示例:

#include <iostream>
using namespace std;

/// <summary>
/// 创建学生结构体
/// </summary>
struct student
{
    
    
    string name;
    int age;
    int scroe;
};

/// <summary>
/// 定义老师结构体
/// </summary>
/// <returns></returns>
struct teacher
{
    
    
    int id;
    string name;
    int age;
    struct student stu;//辅导的学生
};

int main()
{
    
    
    //结构体嵌套结构体
    //创建老师
    teacher t;
    t.id = 10000;
    t.name = "老王";
    t.age = 50;
    t.stu.name = "小李";
    t.stu.age = 20;
    t.stu.scroe = 60;

    cout << "老师姓名:" << t.name << "老师编号:" << t.id << "老师年龄:" << t.age
        <<"老师辅导的学生姓名:"<<t.stu.name<<"老师辅导的学生年龄:"
        <<t.stu.age<<"老师辅导的学生成绩"<<t.stu.scroe << endl;
    system("pause");
}

3、结构体做函数参数
作用:将结构体作为参数向函数中传递。
传递方式有两种:
1)、值传递;
2)、地址传递;
示例:

#include <iostream>
using namespace std;

/// <summary>
/// 定义学生结构体
/// </summary>
/// <returns></returns>
struct  student
{
    
    
    string name;
    int age;
    int score;
};
/// <summary>
/// 打印学生信息函数 值传递
/// </summary>
/// <param name="s"></param>

void printStudent(struct  student s)
{
    
    
    cout << "子函数中 姓名:" << s.name << "年龄:" << s.age << "分数:" <<
        s.score << endl;
}

/// <summary>
/// 地址传递
/// </summary>
/// <param name="p"></param>

void printStudentDring(struct student *p)
{
    
    
    cout << "子函数中 姓名:" << p->name << "年龄:" << p->age << "分数:" <<
        p->score << endl;
}

int main()
{
    
    
    //结构体做函数参数
    //将学生传入到一个参数中,打印学生身上的所有信息

    //创建结构体变量
    struct student s;
    s.name = "张三";
    s.age = 19;
    s.score = 99;

    printStudent(s);
    printStudentDring(&s);

    system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_42291376/article/details/120487687