代码如下 :
static const int NUM = 1000;
const int ARRAY_LENGTH = 10;
想知道加不加 static
有什么区别吗 ?
如果我想将这个常量的使用范围限制在只在该文件中使用, 除了放在类中, 还有什么别的办法吗?
黄舟2017-04-17 14:33:13
If a global variable is modified by static
, it is only visible in this file and cannot be used by other files
Answer your two questions in one go~
怪我咯2017-04-17 14:33:13
static global variables are private for files. If not added, other files can also reference
Just add static
怪我咯2017-04-17 14:33:13
1. Writing outside the function means that it is visible in the current source file (to be precise, the .o object file generated by compilation, because visibility is actually the concept of the linker), which is an internal link. If you don't write it, it will be an external link, and you can use extern to reference this variable in other source files.
a.cpp
static const int A = 0;
const int B = 0;
b.cpp
extern const int A; // 会发生链接错误
extern const int B; // 正确,多数是写在a.h里然后include
Written in a function means it is a static variable. Calling this function multiple times will share the same memory, instead of generating new ones on the stack.
void foo()
{
static const int A = 0; // 多次调用foo,&A不变。
const int B = 0; // 多次调用foo,&B不固定。
}
2. There is a method. For C++, it is recommended to use anonymous space instead of static to make the variables visible in this file.
namespace {
const int MAX_BUFFER_SIZE=200;
}