首页 > 解决方案 > C++ POINTERS(学生 * [n] 给出数组类型不可赋值的错误)

问题描述

#include <iostream>
#include "student.h"

using namespace std;

int main()
{
    // inputting the number of students
    int n;
    cout << "How many students would you like to process?" << endl;
    cin >> n;
    student* s[n];
    string tmp;
    double t;
    // entering each student details
    for (int i = 0; i < n; i++)
    {
        // dynamically allocating object
        s[i] = new student();
        cout << "Enter first name for student " << (i + 1) << endl;
        cin >> tmp;
        s[i]->setFirstName(tmp);
        cout << "Enter middle name for student " << (i + 1) << endl;
        cin >> tmp;
        s[i]->setMiddleName(tmp);
        cout << "Enter last name for student " << (i + 1) << endl;
        cin >> tmp;
        s[i]->setLastName(tmp);
        cout << "Enter GPA for student " << (i + 1) << endl;
        cin >> t;
        s[i]->setGPA(t);
    }
    double avgGPA = 0;
    // printing the student details
    cout << "Students:" << endl;
    cout << "---------" << endl
        << endl;
    for (int i = 0; i < n; i++)
    {
        cout << s[i]->getFirstName() << " " << s[i]->getMiddleName() << " " << s[i]->getLastName() << " " << s[i]->getGPA() << endl;
        avgGPA += s[i]->getGPA();
    }
    avgGPA /= n;
    // printing the average GPA
    cout << endl
        << "Average GPA: " << avgGPA;
    // freeing the memory allocated to objects
    for (int i = 0; i < n; i++)
        delete s[i];
    return 0;
}

在主函数下student * s [n];表示数组类型不可分配给该行。它还给出了表达式必须包含文字的错误。我以为我做的一切都是正确的,但出现了错误。任何人都可以帮助解决此错误的方法是什么?

标签: c++

解决方案


student* s[n];是一个可变长度数组 (VLA),它不在标准 C++ 中。

你应该使用std::vectorlike std::vector<student*> s(n);

还要#include <vector>在代码的开头添加以使用它。


推荐阅读