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

时间:2012-04-03 21:16:12

标签: c++ class static

我在我的班级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 };
//...
};

错误:

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'

我显然没有正确地宣布这一点。声明这个的正确方法是什么?

4 个答案:

答案 0 :(得分:5)

在C ++ 03中,静态数据成员定义在类定义的外部

部首:

#pragma once

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

一个 .cpp文件中:

#include "headername"

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

答案 1 :(得分:5)

在类体内声明

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被禁止,我总是发现各种“重复的限定词”规则完全不合逻辑。

答案 2 :(得分:3)

结合两者:

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

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

答案 3 :(得分:1)

只为Matteo的回答做出贡献:

我们必须指出static限定符确实在C ++中有点令人困惑。据我所知,它根据使用的位置做了三件不同的事情:

  1. 在类成员属性前面:使该属性对于该类的所有实例都相同(与Java相同)。
  2. 在全局变量前面:仅将变量的范围缩小到当前源文件(与C相同)。
  3. 在方法/函数中的局部变量前面:对于该方法/函数的所有调用使该变量相同(与C相同,对单例设计模式可能有用)。
相关问题