1

我正在使用 .h 文件将所有全局变量放在一个文件中,以确保所有文件都可以访问相同的值。但是我有一个 const int,我想知道我应该在哪里对它进行 iisilize?

。H:

#ifndef globalVar_H
#define globalVar_H


const int MAXCPU;
const int MAXPreBorder;

#endif

.cpp:

int MAXCPU=12;
int MAXPreBorder=20;

我想我应该在 .h 文件中声明并在 .cpp 文件中初始化。但是编译器说:

error: non-type template argument of type 'int' is not an integral constant expression

如果我在 .h 文件中初始化。编译器不会抱怨..我想知道这是否是正确的方法?

。H:

#ifndef globalVar_H
#define globalVar_H


const int MAXCPU=12;
const int MAXPreBorder=20;

#endif

.cpp:

//nothing?
4

2 回答 2

3

const变量也是(默认情况下) ,因此对于包含标题static的每个文件,您都有一个唯一的变量。.cpp

因此,您通常希望“就地”初始化它,因为在一个 TU 中定义的实例与您在源文件中初始化的实例不同。

于 2013-06-17T03:07:41.943 回答
1

全局变量.h:

#ifndef globalVar_H
#define globalVar_H


extern const int MAXCPU;
extern const int MAXPreBorder;

#endif

globalVar.cpp:

const int MAXCPU = 12;
const int MAXPreBorder = 20;
于 2013-06-17T03:07:27.370 回答