在 C++ 中,如果两个不同的函数声明相同的静态变量会发生什么?
void foo() {
static int x;
}
void bar() {
static int x;
}
int main() {
foo();
bar();
}
void foo() {
static int x;
}
void bar() {
static int x;
}
int main() {
foo();
bar();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
他们每个人都只看到自己的一个。无法从声明变量的 范围 之外“看到”变量。
如果,另一方面,您这样做了:
然后
foo()
只能看到其本地x
;全局x
已被它“隐藏”。但其中一项的更改不会影响另一项的价值。They each see only their own one. A variable cannot be "seen" from outside the scope that it's declared in.
If, on the other hand, you did this:
then
foo()
only sees its localx
; the globalx
has been "hidden" by it. But changes to one don't affect the value of the other.变量是不同的,每个函数都有自己的作用域。因此,虽然这两个变量在进程的生命周期中持续存在,但它们不会相互干扰。
The variables are distinct, each function has it's own scope. So although both variables last for the lifetime of the process, they do not interfere with each other.
这完全没问题。实际上,编译器输出中变量的实际名称可以被认为是类似于 function_bar_x 的东西,即编译器有责任确保它们不会发生冲突。
This is perfectly fine. In practice the actual name of the variable in the output of the compiler can be thought of as something like
function_bar_x
, i.e. it is the responsibility of your compiler to ensure that these do not clash.什么也没有发生,两个变量都有作用域并保留它们的值以在调用中调用
Nothing happen, both variables have theri scope and mantain their values to call in call
这两个静态变量是不同的。
The two static vars are different.
编译器以独特的方式转换每个变量,例如示例中的
foo_x
和bar_x
,因此它们受到的威胁不同。不要这样做,因为一段时间后您的代码将难以阅读和维护,因为您将无法立即捕获您所指的
x
内容。The compilator translates each variable in a unique manner, such as
foo_x
andbar_x
in your example, so they are threated differently.Don't do this as your code will be hard to read and maintain after some time since you will not able to catch at once of what
x
are you referring to.