试图在类中定义静态常量变量

jak*_*451 3 c++ static class

我在private下定义了一个变量adc_cmd[9]作为static const unsigned char我的类ADC.因为它是一个常数,我想我会在它自己的类中定义它,但这显然不起作用:

#pragma once

class ADC{
private:
    static const unsigned char adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 };
//...
};
Run Code Online (Sandbox Code Playgroud)

错误:

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]'
Run Code Online (Sandbox Code Playgroud)

...

所以我尝试用以下方法将该行带出类: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'
Run Code Online (Sandbox Code Playgroud)

我显然没有正确地宣布这一点.申报这个的正确方法是什么?

ild*_*arn 5

在C++ 03中,静态数据成员定义超出了类定义.

标题:

#pragma once

class ADC {
private:
    static unsigned char const adc_cmd[9];
};
Run Code Online (Sandbox Code Playgroud)

一个 .cpp文件中:

#include "headername"

unsigned char const ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 };
Run Code Online (Sandbox Code Playgroud)


Mat*_*lia 5

你在类体内声明它:

class ADC{
private:
    static const unsigned char adc_cmd[9];
//...
};
Run Code Online (Sandbox Code Playgroud)

并在外部定义(并初始化)(只需一次,就像任何外部链接定义一样):

const unsigned char ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 };
Run Code Online (Sandbox Code Playgroud)

没有写入static,如错误消息所指定.

(不要问我解释为什么这里static被禁止,我总是发现各种"重复的限定词"规则完全不合逻辑)