问题描述
我已经在C代码的不同地方看到了 static
这个词;这就像C#中的静态函数/类(实现在对象之间共享)吗?
I've seen the word static
used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?
推荐答案
- 函数内部的静态变量在调用之间保持其值。
- 仅在其声明的文件中看到静态全局变量或函数
(1)是如果您是新手,那么您会遇到更多的外国话题,因此这里有个例子:
(1) is the more foreign topic if you're a newbie, so here's an example:
#include <stdio.h>
void foo()
{
int a = 10;
static int sa = 10;
a += 5;
sa += 5;
printf("a = %d, sa = %d\n", a, sa);
}
int main()
{
int i;
for (i = 0; i < 10; ++i)
foo();
}
此打印:
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
这在函数需要保持某些状态的情况下非常有用之间的调用,并且您不想使用全局变量。但是要当心,应该非常谨慎地使用此功能-它使您的代码不是线程安全的并且更难以理解。
This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.
(2)被广泛用作访问控制功能。如果您具有实现某些功能的.c文件,则通常仅向用户公开一些公共功能。其其余功能应设为 static
,以便用户无法访问它们。
(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static
, so that the user won't be able to access them. This is encapsulation, a good practice.
引用:
然后回答第二个问题问题,这与C#中的情况不同。
And to answer your second question, it's not like in C#.
在C ++中, static
也用于定义类属性(在相同类的所有对象之间共享)和方法。在C语言中没有类,因此此功能无关。
In C++, however, static
is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.
这篇关于什么是“静态”?在C中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!