简体   繁体   English

结构或类中的数组初始化

[英]Array initialization within a structure or class

I was just studying about structures and classes. 我只是在研究结构和类。 I created a sample structure for getting familiar with it and tried to initialize an array in it. 我创建了一个示例结构来熟悉它,并尝试在其中初始化数组。 when I compiled the program it gave me error 当我编译程序时,它给了我错误

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
char arr[5] = {2,3,8,67,87};

struct abc{
char a;
char b;
char c;

char arr[5] = {2,3,8,67,87};
};  

struct abc xyz[5]; 

Is array initialization not allowed in declaration of a structure as well as class ? 结构和类的声明中是否不允许数组初始化?

I guess in C you can do like this: 我想在C中您可以这样做:

struct abc{
char a;
char b;
char c;

char arr[5];
};  

struct abc test= { 5, 2, 3, { 'a', 'b', 'c', 'd', 'e' } };

In C, you cannot initialize members of a structure in the structure definition. 在C语言中,不能在结构定义中初始化结构的成员。 You have to do it when you declare a variable of that structure. 声明该结构的变量时必须执行此操作。 In C++, you can do it as part of the constructor. 在C ++中,您可以将其作为构造函数的一部分来进行。

Completed array initialization is not allowed in struct but you can just initialize the name and type of array without the content. 不允许在struct中进行完整的数组初始化,但您可以只初始化数组的名称和类型而无需内容。 In c++ 在C ++中

struct student{
int age;
string name;
int scoreOf4subject[4];   
}; 

When you need to set the 4 subjects value in array,it would be like: 当您需要在数组中设置4个主题值时,它将像:

student keny;   
keny.scoreOf4subject={90,91,94,93};

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

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