static关键字的作用

来源:互联网 发布:mac安装win10不能更新 编辑:程序博客网 时间:2024/05/29 16:49

msdn上是这么解释的:

可以用在变量,函数,类数据成员和类函数前面。

By default, an object or variable that is defined outside all blocks has static duration and external linkage. Static duration means that the object or variable is allocated when the program starts and is deallocated when the program ends. External linkage means that the name of the variable is visible from outside the file in which the variable is declared. Conversely, internal linkage means that the name is not visible outside the file in which the variable is declared.

默认的,一个对象或者变量在所有模块外部定义有静态生命期和外部链接。静态生命期意味着这个对象和变量当程序开始时被分配,程序结束时释放。外部链接意味着变量的名字在文件外部是可见的。

关于内部链接和外部链接:

内部连接如果一个名称对于它的编译单元来说是局部的,并且在连接时不会与其它编译单元中的同样的名称相冲突,那么这个名称有内部连接(注:有时也将声明看作是无连接的,这里我们统一看成是内部连接的)。

以下情况有内部连接:
   a)所有的声明
   b)名字空间(包括全局名字空间)中的静态自由函数、静态友元函数、静态变量的定义,const常量定义
   c)enum定义
   d)inline函数定义(包括自由函数和非自由函数)
   e)类的定义
   f)union的定义

   
   外部连接: 在一个多文件程序中,如果一个名称在连接时可以和其它编译单元交互,那么这个名称就有外部连接。
以下情况有外部连接:
   a)类非inline函数总有外部连接。包括类成员函数和类静态成员函数
   b)类静态成员变量总有外部连接。
   c)名字空间(包括全局名字空间)中非静态自由函数、非静态友元函数及非静态变量


The static keyword can be used in the following situations.

  • When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.

  • 当在函数里声明一个变量,static关键字指定了这个变量在调用函数后一直保持它的状态。

  • 当你在类的声明里声明了一个数据成员,static指定所有类的实例共享一份拷贝。一个静态数据成员必须定义在文件作用域里。

  • When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.

  • 当你在一个类的声明里声明一个成员函数,static指定这个函数被类的所有实例共享。一个静态成员函数不能访问实例成员,因为这个函数没有包含这个指针。去访问实例成员,声明带有参数的函数 这是一个实力指针或者引用。

  • You cannot declare the members of a union as static. However, a globally declared anonymous union must be explicitly declared static.

  • 不能在一个union的成员用static。然而,一个全局


0 0
原创粉丝点击