c++ - 如何从 C++ 中的函数返回结构?

标签 c++ function struct return structure

我在几个不同的论坛上尝试过,似乎无法得到一个直接的答案,我怎样才能让这个函数返回结构?如果我尝试'return newStudent;'我收到错误消息“不存在从 studentType 到 studentType 的合适的用户定义转换。”

// Input function
studentType newStudent()
{   
    struct studentType
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;

    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++)
    {   cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    newStudent.avgMarks = calculate_avg(newStudent.arrayMarks,NO_OF_TEST );
    newStudent.courseGrade = calculate_grade (newStudent.avgMarks);

}

最佳答案

这是您的代码的编辑版本,它基于 ISO C++ 并且与 G++ 配合良好:

#include <string.h>
#include <iostream>
using namespace std;

#define NO_OF_TEST 1

struct studentType {
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;
    int arrayMarks[4];
    double avgMarks;
};

studentType input() {
    studentType newStudent;
    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++) {
        cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    return newStudent;
}

int main() {
    studentType s;
    s = input();

    cout <<"\n========"<< endl << "Collected the details of "
        << s.firstName << endl;

    return 0;
}

关于c++ - 如何从 C++ 中的函数返回结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205024/

相关文章:

python - 递归函数计算某个序列出现的次数

c - Fscanf 得到的值错误

c++ - C 中的指针和继承 - 转换问题?

c++ - 返回转发的引用

c++ - 使用 constexpr 时出现编译错误

C++ 异常捕获子句

c# - 如何接受函数引用作为参数?

python - 如何在不中断循环的情况下返回值?

c++ - "Was not declared in this scope"结构定义错误。 C++

c - 了解包含自身类型指针的结构