简体   繁体   English

C ++中的静态全局标识符和非静态全局标识符有什么区别?

[英]What is the difference between static global and non-static global identifier in C++?

是什么区别static全局和非static的C ++全局标识符?

Static limits the scope of the variable to the same translation unit . Static将变量的范围限制为相同的转换单元
A static global variable has internal linkage . 静态全局变量具有内部链接
A non-static global variable has external linkage . 非静态全局变量具有外部链接

Good Read: 好读:
What is external linkage and internal linkage? 什么是外部联系和内部联系?

全局static变量仅在变量所在的转换单元 (即源文件)中可用。可以从其他源文件引用非静态全局变量。

If you don't know what the difference is, correct answer will probably be even more confusing to you. 如果你不知道区别是什么,正确答案可能会让你更加困惑。 In short, static s of a class aren't realted to statics at file scope. 简而言之,类的static s不适用于文件范围的静态。 Statics of a class are esentially identical to regular variables, but they will have to be referenced by prefixing them with class name. 类的静态与常规变量基本相同,但必须通过在类前添加前缀来引用它们。 Statics at file scope are regular variables that are local to the file only. 文件范围的静态是仅对文件本地的常规变量。 To understand what that means, try to add two variables with the same name into a single project. 要了解这意味着什么,请尝试将两个具有相同名称的变量添加到单个项目中。 You will get linker errors because there are multiple identical symbols. 您将收到链接器错误,因为有多个相同的符号。 By making symbols static you will avoid that problems and variable's name won't be accessible from outside the file. 通过使符号静态,您将避免该问题,并且无法从文件外部访问变量的名称。

全局非静态变量可从其他文件访问,而静态全局变量则不可访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM