"Does not name a type"错误,即使我在分配值之前声明
"Does not name a type" error even though I declare right before assigning the values
我已经将问题简化为以下代码:
#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;
}
相关文章:
- 将本地 OpenCV Mat 变量声明为静态以防止重新分配
- 何时在函数中声明堆栈分配变量?
- 新运算符分配的大小大于声明的大小.为什么
- 将模板化实现分配给先前声明的函数
- C++如何使用虚拟基类型声明全局静态分配的变量
- 如何在声明期间将操作分配给复数
- 声明变量以保存字符串列表时的内存分配
- POD 类型是否可以具有显式声明的默认移动分配运算符
- C :如何声明std ::函数而无需创建成员函数以分配给它们
- 在声明节点创建链接列表时,为什么静态内存分配不起作用
- c++:何时初始化声明的变量而不将其分配给任何值
- 在 c++ 中是否有通过声明"implicit"数组分配?
- 只有当声明一个对象时,内存空间才会分配给类的数据成员,那么为什么 Sizeof(class_name) 给我结果
- 如何将值分配给没有值的声明 std::chrono::d uration
- 如何声明数组,然后稍后分配
- 声明指针时的隐式内存分配和初始化
- 如何声明和分配指针
- 声明向量时出现神秘的 malloc 内存分配错误
- 为什么编译器不将内存分配给类内声明的变量
- 声明变量大小数组,而无需使用动态内存分配