什么是“常量静态”在C和C ++是什么意思? [英] What does 'const static' mean in C and C++?

查看:111
本文介绍了什么是“常量静态”在C和C ++是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const static int foo = 42;

我在一些code看到这个位置在计算器上,我无法弄清楚它做什么。然后,我看到其他论坛有些迷糊的答案。我最好的猜测是,它在C用来隐藏其他模块恒。它是否正确?如果是这样,为什么会有人用它在C ++环境在那里你可以让私人

I saw this in some code here on StackOverflow and I couldn't figure out what it does. Then I saw some confused answers on other forums. My best guess is that it's used in C to hide the constant foo from other modules. Is this correct? If so, why would anyone use it in a C++ context where you can just make it private?

推荐答案

它在C和C ++应用

当你猜到了,它的适用范围静态的部分限制到编译单位。它也提供了静态初始化。 常量只是告诉编译器不会让任何人修改它。这个变量要么把在依赖于架构的数据或BSS段,并可能在内存中标记为只读。

As you guessed, the "static" part limits it's scope to that compilation unit. It also provides for static initialization. "const" just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only.

所有这一切是C如何对待这些变量(或C ++如何处理的命名空间的变量)。在C ++中,成员标记静态由给定类的所有实例共享。无论是私人与否不影响一个变量是由多个实例共享这一事实。有'常量'在那里会警告你,如果任何code会尝试修改

All that is how C treats these variables ( or how C++ treats namespace variables ). In C++, a member marked static is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having 'const' on there will warn you if any code would try to modify that.

如果它是严格保密的话,类的每个实例将获得它自己的版本(尽管优化)

If it was strictly private, then each instance of the class would get it's own version ( optimizer notwithstanding)

这篇关于什么是“常量静态”在C和C ++是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆