我没有解决显示如下的问题:student[1].allgrade[1].quiz
部分代码如下。
#include <iostream>
using namespace std;
struct grade
{ int quiz, midterm,final;
};
struct StudentRecord
{
int studentID;
double studentMark;
char letter;
struct grade allgrade[2];
} student[]={
{10,85.2,'A',{70,80,90}},{11,66,'C',{40,50,60}}
};
int main(void)
{
cout<<student[1].allgrade[1].quiz<<"\n";
return 0;
}
根据aggregate initialization的规则,给定初始化程序 {10,85.2,'A',{70,80,90}}
,{70,80,90}
用于初始化第一个元素成员数组allgrade
,然后第二个元素由空列表聚合初始化,其成员quiz
,midterm
和 final
最后是值初始化。 student[1].allgrade[1].quiz
正在尝试访问 allgrade
的第二个元素的 quiz
,然后你会得到 0
(作为值初始化的结果)。
(强调我的)
If the number of initializer clauses is less than the number of members and bases (since C++17)
or initializer list is completely empty, the remaining members and bases (since C++17)
are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14)
by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.
另一方面,student[1].allgrade[0].quiz
会给你结果 40
。
或者您可以显式初始化第二个元素,例如
{10,85.2,'A',{70,80,90}},{11,66,'C',{{40,50,60},{10,20,30}}}
// ^^^^^^^^^^ initializer list for student[1].allgrade[1]
然后 student[1].allgrade[1].quiz
会给你结果 10
。