更新时间:2023-01-12 23:36:23
static
可能是C和C ++中最令人困惑的重载关键字.在不同的地方意味着不同的事情.
static
is probably the most confusingly overloaded keyword in both C and C++. It means different things in different places.
在函数中, static
是一个存储类,表示在程序生命周期内存在的变量.这么说
Within functions, static
is a storage class, denoting variables which exist for the lifetime of the programme. So saying
void f() {
static int i = 0;
}
表示 i
的值将在对 f()
的调用之间保留.其他存储类是默认的 auto
(但要注意C ++ 11中含义的更改), extern
和 register
,以及 thread_local
.
says that the value of i
will be preserved between calls to f()
. Other storage classes are the default auto
(but beware the change in meaning in C++11), extern
, and register
, plus thread_local
in C11/C++11.
在文件范围(或C ++中的命名空间范围), static
是链接说明符.以这种方式标记为 static
的函数和变量具有内部链接,因此对于当前翻译单元而言是本地的.这意味着像
At file scope (or namespace scope in C++), static
is a linkage specifier. Functions and variables marked static
in this way have internal linkage, and so are local to the current translation unit. What this means is that a function like
static int f() {
return 3;
}
只能由同一 .c
文件中的其他函数引用.在C ++ 03中,不推荐使用 static
,而使用未命名的名称空间.我读过某个地方,它在C ++ 11中再次被弃用.
can only be referenced by other functions inside the same .c
file. This usage of static
was deprecated in C++03 in favour of unnamed namespaces. I read somewhere it was undeprecated again in C++11.
在C ++中,当应用于类的成员函数或成员变量时,这意味着该函数或变量不需要类实例即可被访问.在实现方面,类静态"成员函数/变量与全局函数/变量之间几乎没有什么区别,只是C ++类访问说明符适用于成员.
In C++, when applied to a member function or member variable of a class, it means that the function or variable does not need a class instance in order to be accessed. There is little different between "class static" member functions/variables and global functions/variable in terms of implementation, except that C++ class access specifiers apply to members.
最后一个:在C99(但不是C ++)中, static
可以在数组函数参数中使用,如下所示:
One last one: in C99 (but not C++), static
can be used within an array function parameter, like so:
void f(int a[static 4]) {
}
这指定参数 a
必须是大小至少为4的整数数组.
this specifies that the parameter a
must by an integer array of size at least 4.
我想这些都是全部,但是如果您有遗忘的地方,请在评论中告诉我!
I think that's all of them, but let me know in the comments if there are any I've forgotten!