[英]What's the difference between declaration 'static const' and 'const static'
当我用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
变量默认具有内部链接。 因此,如果const
已经存在,则static
关键字不会执行任何操作 - 除了增加可读性。
现在如果你想让变量同时具有外部链接和 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指向的位置)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.