static和const变量有什么区别?

时间:2010-02-07 07:09:41

标签: c++ c static const

有人可以解释staticconst变量之间的区别吗?

17 个答案:

答案 0 :(得分:38)

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

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

答案 1 :(得分:24)

答案简短:

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

static变量意味着对象的生命周期是程序的整个执行,并且它的值仅在程序启动之前初始化一次。如果没有为它们显式设置值,则初始化所有静态。静态初始化的方式和时间是未指定

C99借用了C ++中的const。另一方面,static一直是许多辩论的源头(在两种语言中),因为它经常令人困惑的语义。

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

答案越长:有关关键字的信息比你想知道的更多(从标准开始):

<强> 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 ++

除了简短回答中所述之外,

具有相同的语义。此外,没有参数限定static s。

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
}

我忽略了C ++的static的一些细微差别。看看书或标准。

答案 2 :(得分:7)

静态变量:

  • 仅初始化一次。
  • 静态变量适用于类(不是每个对象)。即每个类只分配一次内存,每个实例都使用它。因此,如果一个对象修改了它的值,那么修改后的值也可以被其他对象看到。 (一个简单的想法..要知道为类创建的对象数量,我们可以放置一个静态变量并在构造函数中执行++)
  • 不同函数调用之间的值

Const变量:

  • Const变量是一个承诺,您不会在程序中的任何位置更改其值。如果你这样做,它会抱怨。

答案 3 :(得分:5)

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

查看此site

答案 4 :(得分:3)

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

在函数中,它仍然是一个持久变量,所以你可以计算一个函数被调用的次数。

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

但是可以防止常量变量发生变化。 const和static的共同使用是在类定义中提供某种常量。

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

答案 5 :(得分:3)

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

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

因此,静态变量仅初始化一次。如果变量在函数中声明,这一点尤为重要,因为它保证初始化只会在首次调用函数时进行。

静力学的另一种用法涉及物体。在对象中声明静态变量会导致该值对于对象的所有实例都相同。因此,不能使用对象的名称来调用它,而只能使用类的名称来调用它。

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

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

答案 6 :(得分:2)

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

const只是常量,意思是无法修改。

答案 7 :(得分:2)

静态变量在所有类型的实例中都很常见。

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

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

答案 8 :(得分:2)

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

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

答案 9 :(得分:1)

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

答案 10 :(得分:0)

static关键字定义变量的范围,而const关键字定义在程序执行期间无法更改的变量值

答案 11 :(得分:0)

简单和简短的回答是内存只为static和const分配一次。但是在const中,只有一个值,静态值可能会改变,但内存区域在程序结束前保持不变。

答案 12 :(得分:0)

不能更改常量变量。静态变量是文件专用的,只能在程序代码中访问,而不能访问其他任何人。

答案 13 :(得分:0)

常量表示“无法更改。”

静态表示“静态实例(在内存中)与动态实例(在栈中)。”静态变量在程序运行期间一直存在。动态的可根据需要创建和销毁。

变量可以是一个或两个。

答案 14 :(得分:0)

  

静态

用于使变量成为类变量。声明时无需定义静态变量。

示例:

#include <iostream>

class dummy
{
        public:
                static int dum;
};


int dummy::dum = 0; //This is important for static variable, otherwise you'd get a linking error

int main()
{
        dummy d;
        d.dum = 1;

        std::cout<<"Printing dum from object: "<<d.dum<<std::endl;
        std::cout<<"Printing dum from class: "<<dummy::dum<<std::endl;

        return 0;
}

这将打印: 从对象打印假对象:1 从班级打印假人:

变量dum是类变量。尝试通过对象访问它只是通知编译器它是哪个类的变量。 考虑一种方案,其中您可以使用变量来计数创建的对象数。静态会派上用场。

  

const

用于使其成为只读变量。您需要立即定义并声明const变量。

在上述相同程序中,我们也将dum设为const:

class dummy
{
        public:
                static const int dum; // This would give an error. You need to define it as well
                static const int dum = 1; //this is correct
                const int dum = 1; //Correct. Just not making it a class variable

};

假设我正在这样做:

int main()
{
        dummy d;
        d.dum = 1; //Illegal!

        std::cout<<"Printing dum from object: "<<d.dum<<std::endl;
        std::cout<<"Printing dum from class: "<<dummy::dum<<std::endl;

        return 0;
}

尽管可以理解static,但是const在c ++中是混乱的。以下资源有助于更好地理解它: http://duramecho.com/ComputerInformation/WhyHowCppConst.html

答案 15 :(得分:0)

const表示常量,它们的值在编译时定义,而不是在运行时显式更改它,在运行时期间不能更改常量值

然而,静态变量是可以在运行时初始化和更改的变量。但是,静态变量与变量的不同之处在于静态变量保留了整个程序的值,即它们的生命周期是程序,或者直到程序通过动态分配方法分配内存。但是,即使它们在程序的整个生命周期内都保留了它们的值,但它们在代码块之外是不可访问的

有关静态变量的更多信息,请参阅here

答案 16 :(得分:-3)

静态值可能存在于函数中,可以以不同的形式使用,并且在程序中可以具有不同的值。 此外,在递减递减后的程序期间,它们的值可能会改变,但在整个程序期间常量不变。