C++ 静态变量和常量变量有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2216239/
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-27 22:35:17  来源:igfitidea点击:

What is the difference between a static and const variable?

c++cstaticconst

提问by jaimin

Can someone explain the difference between a staticand constvariable?

有人可以解释 astaticconstvariable之间的区别吗?

回答by Stefan Kendall

A constant value cannot change. A static variable exists to a function, or class, rather than an instance or object.

常数值不能改变。静态变量存在于函数或类中,而不是实例或对象中。

These two concepts are not mutually exclusive, and can be used together.

这两个概念并不相互排斥,可以一起使用。

回答by dirkgently

The short answer:

简短的回答:

A constis a promise that you will not try to modify the value once set.

Aconst是一个承诺,一旦设置,您将不会尝试修改该值。

A staticvariable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup. All statics are initialized if you do not explicitly set a value to them.The manner and timing of static initialization is unspecified.

static可变装置,所述对象的生存期是程序的整个执行和程序启动之前它的值被初始化仅仅一次。如果您没有为它们显式设置值,则所有静态都将被初始化。静态初始化的方式和时间未指定

C99 borrowed the use of constfrom C++. On the other hand, statichas been the source of many debates (in both languages) because of its often confusing semantics.

C99 借用了constC++ 中的 。另一方面,static由于其经常令人困惑的语义,它一直是许多争论(两种语言)的来源。

Also, with C++0x until C++11 the use of the statickeyword was deprecated for declaring objects in namespace scope. This deprecation was removed in C++11 for various reasons (see here).

此外,在 C++0x 到 C++11 之前static,不推荐使用关键字来声明命名空间范围内的对象。由于各种原因,此弃用已在 C++11 中删除(请参阅此处)。

The longer answer: More on the keywords than you wanted to know (right from the standards):

更长的答案:关于关键字的内容比您想知道的要多(根据标准):

C99

C99

#include <fenv.h>
#pragma STDC FENV_ACCESS ON

/* file scope, static storage, internal linkage */
static int i1; // tentative definition, internal linkage
extern int i1; // tentative definition, internal linkage

int i2; // external linkage, automatic duration (effectively lifetime of program)

int *p = (int []){2, 4}; // unnamed array has static storage

/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // static, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"}  // static, non-modifiable


void f(int m)
{
    static int vla[ m ]; // err

    float w[] = { 0.0/0.0 }; // raises an exception

    /* block scope, static storage, no-linkage */
    static float x = 0.0/0.0; // does not raise an exception
    /* ... */
     /* effect on string literals */
    char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
    char *p = (char []){"/tmp/fileXXXXXX"}; // automatic storage, modifiable
    const char *cp = (const char []){"/tmp/fileXXXXXX"}  // automatic storage, non-modifiable

}

inline void bar(void)
{
     const static int x = 42; // ok
     // Note: Since an inline definition is distinct from the 
     // corresponding external definition and from any other
     // corresponding inline definitions in other translation 
     // units, all corresponding objects with static storage
     // duration are also distinct in each of the definitions
     static int y = -42; // error, inline function definition
}

// the last declaration also specifies that the argument 
// corresponding to a in any call to f must be a non-null 
// pointer to the first of at least three arrays of 5 doubles
void f(double a[static 3][5]);

static void g(void); // internal linkage

C++

C++

Has the same semantics mostly except as noted in the short answer. Also, there are no parameter qualifying statics.

除了简短回答中的说明外,大部分具有相同的语义。此外,没有参数限定statics。

extern "C" {
static void f4(); // the name of the function f4 has
                  // internal linkage (not C language
                  // linkage) and the function's type
                  // has C language linkage.
}

class S {
   mutable static int i; // err
   mutable static int j; // err
   static int k; // ok, all instances share the same member
};

inline void bar(void)
{
     const static int x = 42; // ok
     static int y = -42; // ok
}

There are a few more nuances of C++'s staticthat I leave out here. Have a look at a book or the standard.

static我在这里省略了 C++ 的一些细微差别。看看书或标准。

回答by user3681970

Static Variables:

静态变量:

  • Initialized only once.
  • Static variables are for the class (not per object). i.e memory is allocated only once per class and every instance uses it. So if one object modifies its value then the modified value is visible to other objects as well. ( A simple thought.. To know the number of objects created for a class we can put a static variable and do ++ in constructor)
  • Value persists between different function calls
  • 只初始化一次。
  • 静态变量用于类(不是每个对象)。即每个类只分配一次内存,每个实例都使用它。因此,如果一个对象修改了它的值,那么其他对象也可以看到修改后的值。(一个简单的想法..要知道为类创建的对象数量,我们可以放置一个静态变量并在构造函数中执行 ++ )
  • 值在不同的函数调用之间保持不变

Const Variables:

常量变量:

  • Const variables are a promise that you are not going to change its value anywhere in the program. If you do it, it will complain.
  • Const 变量承诺您不会在程序中的任何地方更改其值。如果你这样做,它会抱怨。

回答by ThunderGr

constis equivalent to #definebut only for value statements(e.g. #define myvalue = 2). The value declared replaces the name of the variable before compilation.

const等效于#define但仅适用于值语句(例如#define myvalue = 2)。声明的值在编译之前替换变量的名称。

staticis a variable. The value can change, but the variable will persistthroughout the execution of the program even if the variable is declared in a function. It is equivalent to a global variable who's usage scope is the scope of the block they have been declared in, but their value's scope is global.

static是一个变量。该值可以更改,但即使在函数中声明了该变量,该变量也会在整个程序执行过程中保持不变。它相当于一个全局变量,其使用范围是声明它们的块的范围,但其值的范围是全局的。

As such, static variables are only initialized once. This is especially important if the variable is declared in a function, since it guarantees the initialization will only take place at the first call to the function.

因此,静态变量只初始化一次。如果变量是在函数中声明的,这一点尤其重要,因为它保证初始化只会在第一次调用函数时发生

Another usage of statics involves objects. Declaring a static variable in an object has the effect that this value is the same for all instances of the object. As such, it cannot be called with the object's name, but only with the class's name.

静态的另一种用法涉及对象。在对象中声明静态变量的效果是该值对于该对象的所有实例都是相同的。因此,不能使用对象的名称调用它,而只能使用类的名称。

public class Test 
{ 
    public static int test;
}
Test myTestObject=new Test();
myTestObject.test=2;//ERROR
Test.test=2;//Correct

In languages like C and C++, it is meaningless to declare static global variables, but they are very useful in functions and classes. In managed languages, the only way to have the effect of a global variable is to declare it as static.

在像 C 和 C++ 这样的语言中,声明静态全局变量是没有意义的,但它们在函数和类中非常有用。在托管语言中,具有全局变量效果的唯一方法是将其声明为静态。

回答by H. Green

Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.

常量不能改变,静态变量更多地与它们的分配方式和可访问的位置有关。

Check out this site.

看看这个网站

回答by Xorlev

Static variables in the context of a class are shared between all instances of a class.

类上下文中的静态变量在类的所有实例之间共享。

In a function, it remains a persistent variable, so you could for instance count the number of times a function has been called.

在函数中,它仍然是一个持久变量,因此您可以例如计算函数被调用的次数。

When used outside of a function or class, it ensures the variable can only be used by code in that specific file, and nowhere else.

在函数或类之外使用时,它确保变量只能由该特定文件中的代码使用,而不能用于其他任何地方。

Constant variables however are prevented from changing. A common use of const and static together is within a class definition to provide some sort of constant.

然而,常量变量被阻止更改。const 和 static 的常见用法是在类定义中提供某种常量。

class myClass {
public:
     static const int TOTAL_NUMBER = 5;
     // some public stuff
private:
     // some stuff
};

回答by celine

A static variable can get an initial value only one time. This means that if you have code such as "static int a=0" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.

静态变量只能获得一次初始值。这意味着,如果您static int a=0在示例函数中有诸如“ ”之类的代码,并且该代码在该函数的第一次调用中执行,但不会在该函数的后续调用中执行;变量 (a) 仍将具有其当前值(例如,当前值为 5),因为静态变量仅获得一次初始值。

A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5", then this value for "a" will be constant in whole of your program.

常量变量的值在整个代码中都是常量。例如,如果您将常量变量设置为“ const int a=5”,那么“a”的这个值将在整个程序中保持不变。

回答by Parveen Kumar

static is a storage specifier.
const is a type qualifier.

回答by invalidopcode

static means local for compilation unit (i.e. a single C++ source code file), or in other words it means it is not added to a global namespace. you can have multiple static variables in different c++ source code files with the samename and no name conflicts.

static 意味着编译单元是本地的(即单个 C++ 源代码文件),或者换句话说,它意味着它没有被添加到全局命名空间中。您可以在不同的 C++ 源代码文件中拥有多个具有相同名称且没有名称冲突的静态变量。

const is just constant, meaning can't be modified.

const 只是常量,意思是不能修改。

回答by this. __curious_geek

Static variables are common across all instances of a type.

静态变量在类型的所有实例中都是通用的。

constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.

常量变量特定于类型的每个单独实例,但它们的值在编译时已知并固定,并且不能在运行时更改。

unlike constants, static variable values can be changed at runtime.

与常量不同,静态变量值可以在运行时更改。