c++中静态变量和普通变量有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5255954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:46:46  来源:igfitidea点击:

what is the difference between static and normal variables in c++?

c++

提问by suma

I need to know the difference,am beginner.

我需要知道区别,我是初学者。

回答by edz007

void func()
{
    static int static_var=1;
    int non_static_var=1;

    static_var++;
    non_static_var++;

    cout<<"Static="<<static_var;
    cout<<"NonStatic="<<non_static_var;
}

void main()
{
    clrscr();
    int i;
    for (i=0;i<5;i++)
    {
        func();
    }
    getch();
}

The above gives output as:

上面给出的输出为:

Static=2
Nonstatic=2

Static=3
Nonstatic=2

Static=4
Nonstatic=2

Static=5
Nonstatic=2

Static=6
Nonstatic=2

Static variable retains its value while non-static or dynamic variable is initialized to '1' every time the function is called. Hope that helps.

每次调用函数时,静态变量保持其值,而非静态或动态变量初始化为“1”。希望有帮助。

回答by Ted Hopp

A static variable is a single memory location associated with the class.

静态变量是与类关联的单个内存位置。

A non-static variable (that is a member of a class) represents a different memory location for each instance of the class.

非静态变量(即类的成员)代表类的每个实例的不同内存位置。

Static variables can be initialized only once and assign to 0 when an object is created.

静态变量只能初始化一次,并在创建对象时赋值为 0。

回答by Nawaz

  • staticnamespace scope variables have internal linkage, while non-staticnamespace scope variables have external linkage by default! Details: a constnamespace scope variable has internal linkage by default. That linkage can by changed by keyword extern.
  • staticvariables in a class is associated with the class, that means, all instances of the class have the same instances of the static variables; they’re like a global variables that every instance of the sameclass has access to.
  • non-staticvariables in a class are instance members, that is, every instance of the class will have its own instances of the non-staticvariables.
  • a staticdata member of a class has external linkage if the name of the class has external linkage. [$3.5/5]
  • a staticvariable inside a function retains its value even after returning from the function. That is, its lifetime is equal to the lifetime of the program itself. This is demonstrated in Mahesh's answer.
  • static命名空间范围变量具有内部链接,而非static命名空间范围变量默认具有外部链接!详细信息const默认情况下,命名空间范围变量具有内部链接。该链接可以通过关键字更改extern
  • static类中的变量与类相关联,即类的所有实例都具有相同的静态变量实例;它们就像一个全局变量,同一个类的每个实例都可以访问。
  • static类中的非变量是实例成员,即类的每个实例都有自己的非static变量实例。
  • static如果类的名称具有外部链接,则类的数据成员具有外部链接。[$3.5/5]
  • static函数内的变量即使从函数返回后仍保留其值。也就是说,它的生命周期等于程序本身的生命周期。这在Mahesh 的回答中得到了证明。

回答by PPatel

Main difference in static and normal variable is in their lifetime, for example scope and lifetime of local variable is within the function-loop in which it is declared, but scope of static variable is same as local variable means it will be accessed within which function it is declared(if not defined globally), but lifetime is through the program. So memory allocation depends on the lifetime, so as static variable will not die till program terminates so no new memory allocated, so fixed memory address allocated to static variables and value in that address will be overwritten every time we change the value of variable, while for normal variable as soon as you will go out of scope, variable will die(means memory will be freed for that variable) and when you will define variable again new memory address will be assigned, new value will be stored in address and no concept of overwrite(when we go out of scope).

静态变量和普通变量的主要区别在于它们的生命周期,例如局部变量的作用域和生命周期在声明它的函数循环内,但静态变量的作用域与局部变量相同意味着它将在哪个函数内访问它被声明(如果没有全局定义),但生命周期是通过程序。因此内存分配取决于生命周期,因此静态变量在程序终止之前不会死亡,因此没有分配新的内存,因此每次我们更改变量的值时,分配给静态变量的固定内存地址和该地址中的值将被覆盖,而对于普通变量,一旦超出范围,变量就会消失(意味着该变量的内存将被释放),并且当您再次定义变量时,将分配新的内存地址,

回答by Swagato

  1. Static members are members that are single shared member common to all the objects created for a particular class but non-static are not so.
  2. Memory allocation is done only once and not every time an object is created like non-static members.
  3. Only one copy of static data member will exist irrespective of the number of objects created.
  4. Static member functions can access only static member variables while a non-static member can be accessed by both static and non-static member functions.
  5. Static members are efficient when single copy of data is enough.
  1. 静态成员是为特定类创建的所有对象共有的单个共享成员,但非静态成员则不然。
  2. 内存分配只进行一次,而不是像非静态成员那样每次创建对象时进行。
  3. 无论创建的对象数量如何,都将只存在一份静态数据成员副本。
  4. 静态成员函数只能访问静态成员变量,而非静态成员可以被静态和非静态成员函数访问。
  5. 当单个数据副本就足够时,静态成员是有效的。

回答by Mahesh

Static variable retains its value during function calls/loops but local variable doesn't;

静态变量在函数调用/循环期间保留其值,但局部变量不会;

#include <iostream>

void foo()
{
    for( int i=0; i<5; ++i )
    {
         static int staticVariable = 0;
         int local = 0;

         ++local;
         ++staticVariable;

         cout << local << "\t" << staticVariable << "\n";
    }
}

int main()
{
    foo();
    return 0;
}

Results:

结果:

1 1
1 2
1 3
1 4
1 5

1 1
1 2
1 3
1 4
1 5

When a static variable is a member of a class, each instance share the static variable. Each instance doesn't have it's own copy.

当静态变量是类的成员时,每个实例共享静态变量。每个实例都没有自己的副本。

class foo
{
     public:
     static int staticVariable;
};

int foo::staticVariable = 0;

foo obj1, obj2 ; // Both the instances share the static variable. 

回答by Mihir Mehta

suppose class Ahas static variable x... and not static variable p

假设class A有静态变量 x... 而不是静态变量 p

now if you create hundred instance of class A (i.e A a;) x would be shared among this hundred instance... but there would be hundred copies of p... one copy of p per instance of A

现在,如果您创建类 A 的一百个实例(即A a;)x 将在这一百个实例之间共享...但是会有一百个 p 的副本...每个 A 实例的一个 p 副本

回答by R4444

Apart from differences in all these answers, there is one more difference between staticand localvariables:

除了所有这些答案的差异之外staticlocal变量之间还有一个差异:

localvariables are stored on the stack, while staticvariables are stored in the datasection of a process memory.

local变量存储在堆栈中,而static变量存储在data进程内存的部分中。

回答by MSalters

There are three different types of "static" variables.

存在三种不同类型的“静态”变量。

  1. Outside functions and classes, a "normal" variable would be a global variable. A staticvariable outside a function is not global, but local to the .cpp file in which it's defined. (Don't define this type of staticvariables in header files!)

  2. Inside a function, a normal variable is destroyed when the function exits. A staticvariable in a function retains its value even after the function exits.

  3. Inside a class, a normal member belongs to an object. A static member is shared between all objects of that type, and even exists before any object of that class is created.

  1. 在函数和类之外,“正常”变量将是全局变量。一个static功能外变量不是全球性的,但当地在其中它被定义.cpp文件。(不要static在头文件中定义这种类型的变量!)

  2. 在函数内部,当函数退出时,普通变量会被销毁。static函数中的变量即使在函数退出后仍保留其值。

  3. 在一个类中,一个普通成员属于一个对象。静态成员在该类型的所有对象之间共享,甚至在创建该类的任何对象之前就存在。