类的const static 成员变量需要在类的定义体外进行定义。示例如下:
/**
* Accout.h
*/
#ifndef ACCOUT_H
#define ACCOUT_H
#include <iostream>
class Accout
{
public:
static void get(std::ostream &os) { os << val; }
private:
const static int val;
};
#endif
/**
* Accout.cpp
*/
#include "Accout.h"
const int Accout::val = 1;
/**
* test.cpp
*/
#include "Accout.h"
using namespace std;
int main() {
Accout a;
Accout::get(cout);
return 0;
}
static成员不能在类的定义体内初始化,而static const成员可以在类的定义体内进行初始化,但同时也需要在类的定义体外进行定义。注意:以下代码在VS2003、VS2008及VS2010上编译不通过,出现变量val重定义的错误,而在g++上编译通过。VS环境中,把类外的val变量定义去掉即编译通过。
/**
* Accout.h
*/
#ifndef ACCOUT_H
#define ACCOUT_H
#include <iostream>
class Accout
{
public:
static void get(std::ostream &os) { os << val; }
private:
const static int val = 10;
int arry[val];
};
#endif
/**
* Accout.cpp
*/
#include "Accout.h"
const int Accout::val;
/**
* test.cpp
*/
#include "Accout.h"
using namespace std;
int main() {
Accout a;
Accout::get(cout);
return 0;
}
References:
C++ primer中文版(第4版)P401-402