C++ 结构指向对象类型错误

C++ Structure Pointer to Object type error

本文关键字:类型 错误 对象 结构 C++      更新时间:2023-10-16

我在C++结构方面遇到了问题。在下面的程序中,我试图从文件中读取考试问题的数量、考试答案以及学生的考试答案文件。这一切都有效,但是当我尝试将学生的信息放入结构的数组中时,由于某种原因,变量 id 不起作用。Microsoft Visual Studio 2017 RC的编译器说"students->id[i]"有一个错误,说:"表达式必须有指向对象类型的指针",我不知道为什么。我标记了问题所在并删除了其余代码,我所拥有的只是正在使用的函数 calculateGrade。我已经为此工作了一段时间,如果不解决这个问题就无法取得任何进展。任何帮助不胜感激!

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct studentInfo {
int id;
string firstName;
string lastName;
string exam;
};
double calculateGrade(struct studentInfo);
int main() {
const int SIZE = 12;
studentInfo students[SIZE];
string fileName, key, studentFile;
ifstream file, fileForStudents;
int numOfQuestions, i = 0, id;
cout << "Please enter a file name: ";
cin >> fileName;
file.open(fileName);
if (!file.is_open()) {
cout << "Could not open file";
}
file >> numOfQuestions >> key >> studentFile;
fileForStudents.open(studentFile);
if (!fileForStudents.is_open()) {
cout << "Could not open file";
}
while (!fileForStudents.eof()) {
fileForStudents >> id >> students->firstName[i] >> students->lastName[i] >> students->exam[i];
students->id[i] = id; //issue is here
i++;
}
calculateGrade(students[SIZE]);

return 0;
}

你只是把索引放在错误的地方 - 它应该是students[i].firstName而不是students->firstName[i]等等,因为数组students

这一行也是不正确的:

calculateGrade(students[SIZE]);

它可以编译,但您将拥有用于越界访问的 UB。如果需要传递整个数组,则将指针传递给第一个元素和大小,但最好使用std::vectorstd::array并通过引用传递它。

因此,对于为什么使用此类代码的其他问题:

students->firstName[i]

编译时,首先students是一个 C 样式数组,它可以隐式衰减到指向第一个元素的指针,因此students->firstName等于students[0].firstName然后students->firstName[i]等于students[0].firstName[i]将访问字符串中的第 i 个符号。

因此,使用std::vector还有另一个原因 - 您的表达式students->firstName[i]不会编译,也不会提供此类代码正确的错误表达式。

students->id只是一个int,它不是一个数组,所以你不能使用students->id[i]

数组是students的,所以它应该是students[i].id的。您不使用->因为students是一个结构数组,而不是一个指针数组。