请求“ ”中非 class 类型“ ”的成员“ ”
request for member ' ' in ' ' which is of non class type ' '
我正在努力克服这个错误。我的函数应该将文件中的数据读入结构数组。
数据文件示例:
1234 52 70 75
2134 90 76 90
3124 90 95 98
结构定义(后面计算平均值):
struct Student
{
int id, testOne, testTwo, testThree;
float average;
};
typedef Student student_array[SIZE];
函数:
void SetArrays (student_array * s)
{
student_array *ptr = s;
fstream fin ("lab5_data.txt");
if (fin.is_open())
{
fin >> ptr->id;
}
}
我不知道如何使用指针算法遍历函数,这是我得到的错误:
[Error] request for member 'id' in '* ptr', which is of non-class type
'student_array {aka Student [20]}'
解决方案:
我能够根据此处给出的建议以及 reddit 解决问题。这是我的解决方案,谢谢大家。
void SetArrays (Student * ptr)
{
//TODO: Function Spec:
fstream fin("lab5_data.txt");
cout << "Data read in:" << endl;
if (fin.is_open())
{
for (int i = 0 ; i < SIZE ; ptr++, i++)
{
fin >> ptr->id;
fin >> ptr->testOne;
fin >> ptr->testTwo;
fin>> ptr->testThree;
student_array是一个数组。
您需要读入该数组的给定元素
像这样
fin >> ptr[0]->id;
你可能想要一个循环并使用循环索引作为数组索引
ptr
是指向数组的指针。
*ptr
取消引用指针,因此结果是一个数组。
(*ptr)[i]
是该数组的一个元素,它是一个 Student
结构。
(*ptr)[i].id
是该结构的成员。
你的代码是错误的,因为它试图用 ->
取消引用 ptr
(到目前为止还不错,ptr
是一个指针,所以取消引用是一个有效的操作),但随后尝试立即获得一个 id
成员,但它仍在查看整个数组。编译器消息大致表示 "you told me to get the id
field of an array, which makes no sense because arrays only have indices, not named fields".
如果你想使用指针运算,摆脱那个typedef
和指向数组的指针业务会更容易:
void SetArrays (Student *ptr)
{
fstream fin ("lab5_data.txt");
if (fin.is_open())
{
while (fin >> ptr->id)
{
ptr++; // advance to the next array element
}
}
}
在此版本中,函数采用指向第一个元素的指针(并使用 ++
逐步遍历数组),而不是指向整个数组的指针。
我正在努力克服这个错误。我的函数应该将文件中的数据读入结构数组。
数据文件示例:
1234 52 70 75
2134 90 76 90
3124 90 95 98
结构定义(后面计算平均值):
struct Student
{
int id, testOne, testTwo, testThree;
float average;
};
typedef Student student_array[SIZE];
函数:
void SetArrays (student_array * s)
{
student_array *ptr = s;
fstream fin ("lab5_data.txt");
if (fin.is_open())
{
fin >> ptr->id;
}
}
我不知道如何使用指针算法遍历函数,这是我得到的错误:
[Error] request for member 'id' in '* ptr', which is of non-class type 'student_array {aka Student [20]}'
解决方案:
我能够根据此处给出的建议以及 reddit 解决问题。这是我的解决方案,谢谢大家。
void SetArrays (Student * ptr)
{
//TODO: Function Spec:
fstream fin("lab5_data.txt");
cout << "Data read in:" << endl;
if (fin.is_open())
{
for (int i = 0 ; i < SIZE ; ptr++, i++)
{
fin >> ptr->id;
fin >> ptr->testOne;
fin >> ptr->testTwo;
fin>> ptr->testThree;
student_array是一个数组。
您需要读入该数组的给定元素
像这样
fin >> ptr[0]->id;
你可能想要一个循环并使用循环索引作为数组索引
ptr
是指向数组的指针。
*ptr
取消引用指针,因此结果是一个数组。
(*ptr)[i]
是该数组的一个元素,它是一个 Student
结构。
(*ptr)[i].id
是该结构的成员。
你的代码是错误的,因为它试图用 ->
取消引用 ptr
(到目前为止还不错,ptr
是一个指针,所以取消引用是一个有效的操作),但随后尝试立即获得一个 id
成员,但它仍在查看整个数组。编译器消息大致表示 "you told me to get the id
field of an array, which makes no sense because arrays only have indices, not named fields".
如果你想使用指针运算,摆脱那个typedef
和指向数组的指针业务会更容易:
void SetArrays (Student *ptr)
{
fstream fin ("lab5_data.txt");
if (fin.is_open())
{
while (fin >> ptr->id)
{
ptr++; // advance to the next array element
}
}
}
在此版本中,函数采用指向第一个元素的指针(并使用 ++
逐步遍历数组),而不是指向整个数组的指针。