我在私有(private)类 ADC
中将变量 adc_cmd[9]
定义为 static const unsigned char
。因为它是一个常量,所以我想我会在它自己的类中定义它,但这显然不起作用:
#pragma once
class ADC{
private:
static const unsigned char adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 };
//...
};
错误:
error: a brace-enclosed initializer is not allowed here before '{' token
error: invalid in-class initialization of static data member of non-integral type 'const unsigned char [9]'
...
所以我尝试使用以下代码将行从类中移出:static const unsigned char ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 };
,但产生了这个错误:
error: 'static' may not be used when defining (as opposed to declaring) a static data member
error: 'const unsigned char ADC::adc_cmd [9]' is not a static member of 'class ADC'
我显然没有正确声明这一点。声明此内容的正确方法是什么?
最佳答案
您在类体内声明它:
class ADC{
private:
static const unsigned char adc_cmd[9];
//...
};
和在外部定义(并初始化)它(仅一次,对于任何外部链接定义):
const unsigned char ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 };
没有写static
,如错误信息所指定。
(不要问我为什么这里禁止static
,我一直觉得各种“重复限定符”规则完全不合逻辑)
关于c++ - 试图在类中定义静态常量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10001518/