使用符号常量声明数组时出现问题
Trouble declaring an array using symbolic constant
此代码无法编译:
#ifndef RemoteControl_h
#define RemoteControl_h
#include "Arduino.h"
class RemoteControl
{
public:
RemoteControl();
~RemoteControl();
static void prev_track();
static void next_track();
static void play_pause_track();
static void mute();
static void vol_up();
static void vol_down();
void respond(int code);
void add_code(int code, void (*func)());
private:
boolean active = true;
struct pair {
int _code;
void (*_func)();
};
const int max = 1000;
int database_length = 0;
pair database[max]; //This line doesn't compile unless I use a literal constant instead of "max"
};
#endif
但是如果我把下面的部分放在类的构造函数中,它就会正常工作。
const int max = 1000;
int database_length = 0;
pair database[max];
我不允许在c++类中声明数组并使用虚常量作为长度吗?我正在arduino工作,如果这有什么不同,但我希望我不理解c++语言的东西,因为这是一个标准的。h文件。哦,问题不在于.cpp文件,因为我完全删除了它,结果相同:使用文字常量长度编译,而不是虚拟常量长度。
在C或c++中,尝试在stdlib.h
中使用malloc()
, cstdlib
用于c++。别忘了free()
const int max = 1000;
struct pair *ptr = malloc(sizeof(pair) * max); // allocated 1000 pairs
free(ptr); // when the amount of memory is not needed anymore
让我先为你澄清一些事情。
-
在
C
中,const
变量被认为是const
限定的,它不是编译时常量值(不像整数字量,它是编译时常量值)。因此,根据常规数组大小规范的规则,在这种情况下,您甚至不能使用const
变量。 -
在
C
中,我们可能有使用VLA的规定,这使我们能够使用像pair database[max]
这样的语法,即使max
不是const
变量,但这又是编译器的一些可选功能(根据C11
)。 -
在
C++
中,我们可以使用const
变量作为数组的大小,在C++
中,const
变量是编译时常数。
那么,回答你的问题:
- 在
C
中,如果你的编译器支持VLA,你的代码就可以了。即使max
不是const
。 - 在
C++
中,没有VLA,但它可能作为gnu扩展支持。如果max
是const
,就可以了。
最简单的解决方法就是将
const int max = 1000;
脱离类并置于类之上。
更好的方法是确保它是一个编译时常量,像这样:
constexpr int max = 1000;
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 输入std::数组时出现问题
- 类对象数组的问题会导致崩溃
- 传递二维数组时出现问题
- 从 C++ 中的函数返回数组地址问题
- 使用数组时出现问题
- 打印问题.我在数组中打印值时遇到一些问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 将字节数组转换为带有字节序问题的指针
- C++ 填充数组时遇到问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 当我尝试通过 arduino 上的引用传递布尔数组时出现问题
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 编写 cin.get() 以接收字符数组时出现问题
- 在 C++ Consol 中的数组中执行用户命令时出现问题
- 存储另一个函数返回的布尔数组时遇到问题
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 运行时C++数组初始化问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组