声明'static const'和'const static'之间有什么区别

Xin*_*uan 4 c++

当我用C++做声明时,

static const int SECS = 60 * MINUTE;
const static int SECS = 60 * MINUTE;
Run Code Online (Sandbox Code Playgroud)

这两者有什么区别吗?

Naw*_*waz 9

这两者有什么区别吗?

一点都不.订单无关紧要(在这种情况下!).

而且,如果你写这个:

const int SECS = 60 * MINUTE; //at namespace level
Run Code Online (Sandbox Code Playgroud)

在命名空间级别,那么它等同于:

static const int SECS = 60 * MINUTE;
Run Code Online (Sandbox Code Playgroud)

因为在命名空间级别, const变量默认具有内部链接.因此,除非增加可读性,否则static关键字不会执行任何操作const.

现在,如果您希望变量具有外部链接, const同时又要使用extern:

//.h file 
extern const int SECS;   //declaration

//.cpp file
extern const int SECS = 60 * MINUTE; //definition
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


cod*_*ing 7

const始终适用于其左边的类型; 如果没有,则适用于右侧的下一个类型.

所以以下三个声明

const static int SECS = 60 * MINUTE;
// or
static const int SECS = 60 * MINUTE;
// or
static int const SECS = 60 * MINUTE;
Run Code Online (Sandbox Code Playgroud)

都是平等的.static适用于整个声明; 和const适用于该int类型.

const如果你有一个"更复杂"的类型,例如引用或指针,那么位置只会产生影响:

int a;
const int * b = a; // 1.
int * const c = a; // 2.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它的位置之间存在差异const- 对于1.它适用于int(即它是指向const int的指针,即您不能更改该值),而对于2.,它适用于指针(即你无法修改c指向的位置).