当我在 C++ 中声明时,
static const int SECS = 60 * MINUTE;
const static int SECS = 60 * MINUTE;
这两者有什么区别吗?
当我在 C++ 中声明时,
static const int SECS = 60 * MINUTE;
const static int SECS = 60 * MINUTE;
这两者有什么区别吗?
这两者有什么区别吗?
一点都不。顺序无关紧要(在这种情况下!)。
此外,如果你这样写:
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
希望有帮助。
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.
在这种情况下, - 的位置有区别const
1. 它适用于 int(即它是指向 const int 的指针,即您不能更改值),而对于 2.,它适用于指针(即您不能修改 c 指向的位置)。