尝试在类中定义静态常量变量 [英] Trying to define a static constant variable in a class

查看:150
本文介绍了尝试在类中定义静态常量变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类<$ c中将变量 adc_cmd [9] 定义为静态const无符号字符 $ c> ADC 在私有下。因为它是一个常数,所以我想只在它自己的类中定义它,但这显然不起作用:

I am defining a variable adc_cmd[9] as a static const unsigned char in my class ADC under private. Since it is a constant I thought I would just define it inside the class it self, but that didn't work apparently:

#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}; ,但是会产生此错误:

So I tried bringing the line out of the class with: static const unsigned char ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 };, but that yielded this error:

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'

我显然没有正确地声明这一点。声明此内容的正确方法是什么?

I obviously am not declaring this properly. What is the correct way to declare this?

推荐答案

声明它在类体内:

class ADC{
private:
    static const unsigned char adc_cmd[9];
//...
};

define (并初始化)它在外部(仅一次)任何外部链接定义):

and define (and initialize) it outside (just once, as for any external-linkage definition):

const unsigned char ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 };

不写 static ,错误消息。

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

(don't ask me for an explanation of why here static is forbidden, I always found the various "repetition of qualifiers" rules completely illogic)

这篇关于尝试在类中定义静态常量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆