const和静态const的区别是什么?

What is the difference of const and static const?

本文关键字:const 是什么 区别 静态      更新时间:2023-10-16

以下语句都是有效的:

static const A = 2;
const B = 3;

声明第一个和第二个有什么区别?

如果在类中声明static const,则可以从类和类的任何实例访问它,因此所有这些都将共享相同的值;单独的const对于该类的每个实例都是互斥的。

给定类:

class MyClass {
    public:
        static const int A = 2;
        const int B = 4;
};

你可以这样做:

int main() {
    printf("%d", MyClass::A);
    /* Would be the same as */
    MyClass obj;
    printf("%d", obj.A);
    /* And this would be illegal */
    printf("%d", MyClass::B);
}

在Ideone上查看

Static表示整个类只共享1个const,而非Static表示类的每个实例都单独拥有该const。

的例子:

class A{
static const a;
const b; 
}
//Some other place:
A m;
A n;

对象m和n具有相同的a,但不同的b。