c++ - 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];
表示数组类型不可分配给该行。它还给出了表达式必须包含文字的错误。我以为我做的一切都是正确的,但出现了错误。任何人都可以帮助解决此错误的方法是什么?
解决方案
student* s[n];
是一个可变长度数组 (VLA),它不在标准 C++ 中。
你应该使用std::vector
like std::vector<student*> s(n);
。
还要#include <vector>
在代码的开头添加以使用它。
推荐阅读
- node.js - nodejs - 如何防止exif图像自动旋转
- python - 是否有 asyncio 的 `call_at` 或 `call_later` 对于 anyio 的等价物?
- node.js - 在 MongoDB 中通过对象 id 抓取另一个对象内部的对象
- java - fcm 使用 java(tomcat) 推送发送
- python - Discord.py 带线程,RuntimeError: Timeout 上下文管理器应该在任务内部使用
- python - Python:迭代一系列数字作为 Plotly Dash 的输入
- c# - 构建项目后可以通过 ML-Agent 学习吗?
- sql - 如何在 Postgres 中求和
- c++ - 使用 std::sort 中的 lambda 函数指定的比较函数是否返回 bool 类型?
- sql - 我应该如何优化此行级安全策略以读取事件?