使用符号常量声明数组时出现问题

Trouble declaring an array using symbolic constant

本文关键字:问题 数组 符号常量 声明      更新时间:2023-10-16

此代码无法编译:

#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

让我先为你澄清一些事情。

  1. C中,const变量被认为是const限定的,它不是编译时常量值(不像整数字量,它是编译时常量值)。因此,根据常规数组大小规范的规则,在这种情况下,您甚至不能使用const变量。

  2. C中,我们可能有使用VLA的规定,这使我们能够使用像pair database[max]这样的语法,即使max不是const变量,但这又是编译器的一些可选功能(根据C11)。

  3. C++中,我们可以使用const变量作为数组的大小,在C++中,const变量是编译时常数。

那么,回答你的问题:

  • C中,如果你的编译器支持VLA,你的代码就可以了。即使max不是const
  • C++中,没有VLA,但它可能作为gnu扩展支持。如果maxconst,就可以了。

最简单的解决方法就是将

const int max = 1000;

脱离类并置于类之上。

更好的方法是确保它是一个编译时常量,像这样:

constexpr int max = 1000;