用C静态和静态的C ++之间的差异? [英] Difference between static in C and static in C++??

查看:142
本文介绍了用C静态和静态的C ++之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是C和C ++中的static关键字?

之间的区别
解决方案

静态关键字服务于C和C相同的目的++。


  1. 当在文件级使用(外一功能),它会将它应用到项目的知名度。静态项不是他们编译单元的外部看到(例如,接头)。它们的持续时间是一样的节目的持续时间。搜索结果
    除非有特定需要从外部访问它们(而且也几乎从来没有必要给予直接存取数据,因为这打破了封装的核心原则),这些文件级项目(功能和数据)应该是静态的。结果< BR>
    如果(至于问题的评论所指出的)这是静态您关注的是,再没有,有C和C ++之间没有差异。


  2. 在一个函数中使用,它设置项目的持续时间。再次,持续时间是一样的程序和项目继续该函数的调用之间存在。搜索结果
    因为它只在函数的可见它不影响该项目的知名度。一个例子是一个随机数发生器,需要保持调用之间的种子值,但不希望其他功能可见该值


  3. C ++多了一个使用静态 A类中。使用时在那里,就变成一个类变量这是跨类的所有对象的公共。一个典型的例子是存储已实例化对于给定的类对象的数目


正如其他人所指出的那样,使用文件级静态一直赞成无名的命名空间pcated德$ P $。不过,我相信之前它实际上是从语言中删除这将是一个寒冷的日子一定暖和的地方 - 有使用它此刻只是太多code。和ISO C仅有的只是的得到解决,以去除获得(),尽管我们都知道这是一个危险的函数的时间。

和即使它pcated德$ P $,这并没有改变其语义的现在

What is the difference between the static keyword in C and C++?

解决方案

The static keyword serves the same purposes in C and C++.

  1. When used at file level (outside of a function), it sets the visibility of the item it's applied to. Static items are not visible outside of their compilation unit (e.g., to the linker). Their duration is the same as the duration of the program.

    These file-level items (functions and data) should be static unless there's a specific need to access them from outside (and there's almost never a need to give direct access to data since that breaks the central tenet of encapsulation).

    If (as your comment to the question indicates) this is the only use of static you're concerned with then, no, there is no difference between C and C++.

  2. When used within a function, it sets the duration of the item. Again, the duration is the same as the program and the item continues to exist between invocations of that function.

    It does not affect the visibility of that item since it's visible only within the function. An example is a random number generator that needs to keep its seed value between invocations but doesn't want that value visible to other functions.

  3. C++ has one more use, static within a class. When used there, it becomes a single class variable that's common across all objects of that class. One classic example is to store the number of objects that have been instantiated for a given class.

As others have pointed out, the use of file-level static has been deprecated in favour of unnamed namespaces. However, I believe it'll be a cold day in a certain warm place before it's actually removed from the language - there's just too much code using it at the moment. And ISO C have only just gotten around to removing gets() despite the amount of time we've all known it was a dangerous function.

And even though it's deprecated, that doesn't change its semantics now.

这篇关于用C静态和静态的C ++之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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