这段代码不会编译:
#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()
,在 C++ 中使用 cstdlib
。不要忘记 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++ - 使用符号常量声明数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32149843/