[英]C++ POINTERS (student * [n] gives the error that array type is not assignable)
#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;
}
Under the main function student * s [n];
主下function student * s [n];
says the array type is not assignable to the line.It also gives an error that the expression must contain a literal.表示数组类型不可分配给该行。它还给出了表达式必须包含文字的错误。 I thought I was doing everything right, but there was an error.我以为我做的一切都是正确的,但出现了错误。 What is the solution to this error can anyone help?任何人都可以帮助解决此错误的方法是什么?
student* s[n];
is a Variable-Length Array (VLA) , which is not in the standard C++.是一个可变长度数组 (VLA) ,不在标准 C++ 中。
You should use std::vector
like std::vector<student*> s(n);
你应该使用std::vector
像std::vector<student*> s(n);
. .
Also add #include <vector>
at the beginning of your code to use that.还要在代码的开头添加#include <vector>
以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.