2012-04-03 34 views
3

定义一个静态常量变量,我在我的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' 

我显然没有正确地宣布这一点。什么是正确的方式来宣布这一点?

回答

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

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 }; 
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 }; 
1

只是为了促进利玛窦的答案:

我们必须指出在C++中static限定符确实有点令人困惑。据我所知,它取决于它在哪里使用三种不同的东西:

  1. 在类成员属性前:使该属性对该类的所有实例(与Java相同)都是相同的。
  2. 在全局变量前面:仅将变量的作用域缩小为当前源文件(与C相同)。
  3. 在方法/功能中的局部变量的前面:使得这个变量相同的用于向方法/函数的所有调用(同C,可以是用于单例设计模式是有用的)。