使用符号常量

时间:2015-08-21 21:57:37

标签: 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文件,因为我用相同的结果完全删除了它:用文字常量长度编译但不是虚拟常量长度。

3 个答案:

答案 0 :(得分:1)

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

  1. C中,const变量被视为const - 限定,它不是编译时常量值(与整数文字不同,这是一个编译时间常数值)。因此,根据正常数组大小规范的规则,在这种情况下甚至无法使用const变量。

  2. C中,我们可能有使用VLA的条款,即使pair database[max]也可以使用max之类的语法}不是const变量,而是编译器的一些可选功能(根据C11)。

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

  4. 所以,回答你的问题:

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

答案 1 :(得分:1)

在C或C ++中,尝试在malloc()中使用stdlib.h,在{+ 1}}中使用c ++。别忘了cstdlib

free()

答案 2 :(得分:0)

最简单的解决方法就是采取

const int max = 1000;

走出课堂,把它放在课堂上面。

更好的方法是确保它是一个编译时常量,如下所示:

constexpr int max = 1000;
相关问题