用户工具

站点工具


c

这是本文档旧的修订版!


Static&Const

const是单词constant的简写,字面意思是常数、常量。用于变量修饰,表明这个变量不能被修改;用于指针修饰,表明指针的指向物不能被修改;用于方法修饰,表明这个方法不会对对象造成改变。

const int foo = 1;
foo = 2; // compile time error

const int* ptr = &foo;
*ptr = 3 // compile time error

int fuck = 0;
ptr = &fuck; // this is OK
*ptr = 123; // compile time error

struct FooBar
{
    int member;
    int MyMethod(int value) const
    {
        member = value; // compile time error
    }
};
  static很讨厌,有三个个完全不同的含义:用在全局变量,表明这个变量在每个编译单元有独自的实例:
// foo.h
static int a = 123;// foo.cpp
#include "foo.h"
int foo_func() { return a++; }
// bar.cpp
#include "foo.h"
int bar_func() { return a++; }

如果你分别编译foo.cpp和bar.cpp,再把它们链接在一起,全局变量a会有两份,那两个函数会操纵不一样的a实例。用在函数里的局部变量,表明它的生存周期其实是全局变量,但仅在函数内可见:

int get_global_id()
{
    static int seed = 0;
    return seed++;
}

每次访问这个函数的时候,会获得不同的int值。那个=0的操作仅在第一次访问时执行,其实是初始化而不是赋值。用在类成员,表明成员或者方法是类的,而不是对象实例的。

struct Foo
{
    int a = 0;
    static int aaa = 0;
    static int bbb() { return 123456; }
};

每个Foo实例会只含有一个int a。bbb方法通过Foo::bbb()调用。

c.1639270833.txt.gz · 最后更改: 2021/12/12 09:00 由 admin