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

标签 c++ class static

我在私有(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/

相关文章:

java - 在 Java 中,接收器到底是什么或者接收器到底可以是什么?

java - 静态方法是否应该与具有实例方法的类分开?

eclipse - 如何在 Eclipse IDE 中查找完整的警告列表

c++ - 美化 Win32 应用程序中的工具提示

c++ - 多个字符串::查找

c++ - lldb在clang++编译时无法调试字符串

c++ - STL iota 包含文件更改

swift - 我正在尝试快速创建 UIImageView 的子类以添加一个简单的计数器

c++ - 使用断言参数存在的参数化类创建。使用工厂?

java - _ClassInstance 符号?