c++ - 使用符号常量声明数组时遇到问题

标签 c++ arduino

这段代码不会编译:

#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/

相关文章:

C++在派生类指针数组上调用虚函数

c++ - 整数位移

c++ - std::map::lower_bound 正在为大于 2000 的映射键生成核心转储

Java - Arduino - 使用 IDE 上传草图时出错(禁用 GUI),但它可以从命令行运行

c++ - 将SD卡上存储的电话号码插入短信发送AT命令Arduino

c++ - 可调用结果类型的推导

c++ - 如何在 C++ 中使用 SQLGetData 获取 MySQL blob 作为二进制数据

c++ - 这个 for 循环可以用预处理器完成吗?

processing - Processing/Arduino中如何计算统计模式

c++ - 如何在 Arduino 延迟期间在 void loop() 中使用 serial.available()?