C++ 结构指向对象类型错误
C++ Structure Pointer to Object type error
我在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::vector
或std::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
是一个结构数组,而不是一个指针数组。
- 类没有命名C++代码中的类型错误
- 不完整类型错误(E0409、E0070、E0515)
- 使用具有结构不完整类型错误的模板
- 不命名构造函数和析构函数上的类型错误
- 返回派生类型时出现协变类型错误
- 为什么此构造函数没有给出不完整的类型错误?
- 定义模板化结构的特征时出现不完整的类型错误
- 使用重载构造函数时出现不完整的类型错误
- 为什么我得到表达式必须有类类型错误?
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 枚举成员不是类型错误
- 如何修复"ctypes"。参数错误:参数 2:<键入"异常.类型错误">:RaspberryPi 中的错误类型"错误
- 外部 "C" Visual Studio 2015 中的显式类型错误,DLL 测试代码
- 非默认析构函数会导致不完整的类型错误
- 为什么按引用传入会导致绑定引用类型错误
- Objective-C C++ 包装器 类型错误的不完整定义
- 输入类型错误
- 当构造函数的参数类型错误时引发异常
- 命名空间中的'bad_cast' 'std' 未命名类型错误
- C UNWORKOWN类型错误