c++ - C++ 中的结构与数组

标签 c++ initialization

<分区>

我没有解决显示如下的问题: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,然后第二个元素由空列表聚合初始化,其成员quizmidtermfinal 最后是值初始化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

关于c++ - C++ 中的结构与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53666743/

相关文章:

c++ - 摆脱字符串文字末尾的\0 的最佳方法是什么?

c++ - 为什么在财务计算中应该使用十进制 float ,但它有舍入误差

c++ - 尝试动态增加数组大小

C++ 设置方法 : function 'setCost' not viable: 'this' argument has type 'const value_type'

c++ - 调整 vector 大小并检索值,这是正确的还是在任何情况下都可能导致段错误?

objective-c - 重新定义父类声明为 NS_UNAVAILABLE 的初始化器

c++ - 为什么矩阵没有正确初始化/打印?

objective-c 类的默认初始化方法?

c++ - 是否可以在 C++ 中声明具有不同类型的变量?

c - 可变大小的对象可能未被初始化