"Does not name a type"错误,即使我在分配值之前声明

"Does not name a type" error even though I declare right before assigning the values

本文关键字:分配 声明 not Does name 错误 type      更新时间:2023-10-16

我已经将问题简化为以下代码:

#include <iostream>
using namespace std;
struct hello
{
    int array[4];
    array[0] = 1;
    array[1] = 2;
    array[2] = 3;
    array[3] = 4;
};

当我编译这个时,我仍然得到"数组不命名类型"错误,在我赋值的每一行。我想这个错误是在变量被声明的时候引起的,即使我在赋值的右边声明了数组。

赋值语句 like array[0] = 0;不能进入结构体定义,需要进入可执行代码块,如函数、构造函数或类似的代码块。

struct hello
{
    int array[4];
    hello(){
        array[0] = 1;
        array[1] = 2;
        array[2] = 3;
        array[3] = 4;
    }
};

应该在结构体定义外赋值,而不是在结构体定义内赋值。

#include <iostream>
struct hello
{
    int array[4];
};
int main()
{
    hello h;
    h.array[0] = 1;
    h.array[1] = 2;
    h.array[2] = 3;
    h.array[3] = 4;
    // do stuff
    return 0;
}

在c++中不能这样初始化数组。有几种方法可以解决这个问题:

1)创建一个构造函数(这将初始化hello的每个实例具有相同的值):

struct hello {
    int array[4];
    hello() {
        array[0] = 1;
        array[1] = 2;
        array[2] = 3;
        array[3] = 4;
    }
};
hello h;

2)用相应的值初始化hello的每个实例(不同的实例可以有不同的值):

struct hello
{
    int array[4];
};
hello h = {{1,2,3,4}};

这里还有一种使用静态变量的可能性,因为您的意图没有明确说明:

struct hello
{
    static int array[4];
};
int hello::array[4];
int main()
{
    hello::array[0] = 1;
    return 0;
}