4

当我在 C++ 中声明时,

static const int SECS = 60 * MINUTE;
const static int SECS = 60 * MINUTE;

这两者有什么区别吗?

4

2 回答 2

9

这两者有什么区别吗?

一点都不。顺序无关紧要(在这种情况下!)。

此外,如果你这样写:

const int SECS = 60 * MINUTE; //at namespace level

在命名空间级别,则相当于:

static const int SECS = 60 * MINUTE;

因为在命名空间级别 const变量默认具有内部链接。因此,static如果关键字已经存在,则不会做任何事情const——除了增加可读性。

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

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

//.cpp file
extern const int SECS = 60 * MINUTE; //definition

希望有帮助。

于 2013-11-08T09:00:40.613 回答
7

const总是适用于紧挨着它的左边的类型;如果没有,则适用于其右侧的下一个类型。

所以下面三个声明

const static int SECS = 60 * MINUTE;
// or
static const int SECS = 60 * MINUTE;
// or
static int const SECS = 60 * MINUTE;

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

只有当你有一个“更复杂”的类型时,位置const才会有所不同,比如引用或指针:

int a;
const int * b = a; // 1.
int * const c = a; // 2.

在这种情况下, - 的位置有区别const1. 它适用于 int(即它是指向 const int 的指针,即您不能更改值),而对于 2.,它适用于指针(即您不能修改 c 指向的位置)。

于 2013-11-08T09:02:44.483 回答