[031] C++函数返回结构体类型数据

1、代码简介

① 结构体包含学生的三类信息:年龄,成绩,姓名;

② func函数用于求和各科成绩,并返回总分最高的学生的结构体数据;

③ 关键:用指针等效数组;用结构体指针返回结构体类型数据。

2、代码

① main.cpp

#include <iostream>
#include <string>
#include <cstdio>
#include "func.h"

using namespace std;

//学生信息赋值
int age1 = 10;
double scores1[3] = {122.2, 123.2, 94.8};
string name1 = "zhangsan";
int age2 = 11;
double scores2[3] = {112.9, 203.2, 114.8};
string name2 = "lisi";
student zhangsan = {age1, scores1, name1};
student lisi = {age2, scores2, name2};

//定义一个student结构体指针,用于接收函数运行后返回的结果
student *get_answer;

int main()
{
    get_answer = brilliant(zhangsan, lisi);
    cout  << get_answer->name  <<  " is more brilliant" << endl;
    return 0;
}

② func.cpp

#include "func.h"

student *brilliant(student A_people, student B_people)
{
    student *answer_people;                //定义一个student结构体类型的指针,返回函数运算结果
    double A_total_scores, B_total_scores; //定义两个变量,代表两位同学的总分

    A_total_scores = A_people.scores[0] + A_people.scores[1] + A_people.scores[2];
    B_total_scores = B_people.scores[0] + B_people.scores[1] + B_people.scores[2];

    if (A_total_scores >= B_total_scores)
    {
        answer_people = &A_people;
    }
    else
    {
        answer_people = &B_people;
    }
    return answer_people;
}

③ func.h

#include <string>
using namespace std;

typedef struct
{
    int age;        //年龄
    double *scores; //分数,由于是多科成绩,所以此处定义一个指针,后续以数组赋值的方式将成绩传入该指针
    string name;    //姓名
} student;

extern student *brilliant(student A_people, student B_people);

当然,也可以的将上面三个文件汇总成一个main文件:

#include <iostream>
#include <string>
#include <cstdio>

using namespace std;

typedef struct
{
    int age;        //年龄
    double *scores; //分数,由于是多科成绩,所以此处定义一个指针,后续以数组赋值的方式将成绩传入该指针
    string name;    //姓名
} student;

//学生信息赋值
int age1 = 10;
double scores1[3] = {122.2, 123.2, 94.8};
string name1 = "zhangsan";
int age2 = 11;
double scores2[3] = {112.9, 203.2, 114.8};
string name2 = "lisi";
student zhangsan = {age1, scores1, name1};
student lisi = {age2, scores2, name2};

//定义一个student结构体指针,用于接收函数运行后返回的结果
student *get_answer;

student *brilliant(student A_people, student B_people)
{
    student *answer_people;                //定义一个student结构体类型的指针,返回函数运算结果
    double A_total_scores, B_total_scores; //定义两个变量,代表两位同学的总分

    A_total_scores = A_people.scores[0] + A_people.scores[1] + A_people.scores[2];
    B_total_scores = B_people.scores[0] + B_people.scores[1] + B_people.scores[2];

    if (A_total_scores >= B_total_scores)
    {
        answer_people = &A_people;
    }
    else
    {
        answer_people = &B_people;
    }
    return answer_people;
}

int main()
{
    get_answer = brilliant(zhangsan, lisi);
    cout  << get_answer->name  <<  " is more brilliant" << endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值