繁体   English   中英

在结构中分配数组字段

[英]Assign array field within struct

最近我开始研究 C++ 代码,我试图与一个外部库进行通信,该库的结构定义如下

struct StudentsInformation {
    int student_count[10];
    double total_marks[10];
    double section_marks_average;
    double class_marks_average;
};

我试图在单独的 class 中为此结构创建 object

int count[10] = {1, 2, 3, 4, 5, 1, 2, 3, 4, 5}; 
double marks[10] = {10.0, 20.0, 30.0, 40.0, 50.0, 10.0, 20.0, 30.0, 40.0, 50.0};

StudentsInformation stuInfo = { count, marks, 68.8, 56.7 };

编译它会提供以下错误

无法使用“int [10]”类型的左值初始化“int”类型的数组元素

不知道我做错了什么。

这应该可以很好地编译,在 C 和/或 C++ 中的一个/两个中:

#include <stdio.h>

struct StudentsInformation {
    int student_count[10];
    double total_marks[10];
    double section_marks_average;
    double class_marks_average;
};

int main(int argc, char *argv[]) {
  struct StudentsInformation si = {
    {1, 2, 3, 4, 5, 1, 2, 3, 4, 5},
    {10.0, 20.0, 30.0, 40.0, 50.0, 10.0, 20.0, 30.0, 40.0, 50.0},
    68.8, 56.7
  };

  return 0;
}

错误消息的关键部分是“无法转换左值”:

https://en.cppreference.com/w/cpp/language/value_category

左值

变量的名称、function、模板参数 object(C++20 起)或数据成员的名称,无论类型如何,例如 std::cin 或 std::endl。 即使变量的类型是右值引用,由其名称组成的表达式也是左值表达式;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM