C++结构体做函数参数

410 阅读1分钟
#include<iostream>
using namespace std;
#include <string>

/*
结构体做函数参数
作用:将结构体作为参数向函数中传递
传递方式:
1. 值传递
2. 地址传递
总结:入宫不想修改主函数中的数据,用值传递,反之用地址传递
*/

//1. 创建学生数据类型 
struct  student
{
    //姓名
    string name;
    //年龄
    int age;
    //分数
    int score;
};

//打印学生信息
//1.值传递
void printStudent1(struct student s)
{
    cout << "子函数1中 姓名:" << s.name << "年龄:" << s.age << "分数:" << s.score << endl;
}

//2. 地址传递
void printStudent2(struct student *p)
{
    cout << "子函数2中 姓名:" << p->name << "年龄:" << p->age << "分数:" << p->score << endl;
}


int main(){
    
    //结构体作为函数参数

    //将学生传入到一个参数中,打印学生身上的所有信息

    //创建结构体变量
    struct  student s;
    s.name = "张三";
    s.age = 20;
    s.score = 85;
    
    printStudent1(s);
    printStudent2(&s);

    system("pause");
    return 0;
}