为什么我需要静态?

时间:2020-12-25 02:06:52

Why I can write this:

为什么我可以写这个:

class VoiceManager
{
public:
    static const int mMaxNumOfVoices = 16;
    Voice mVoices[mMaxNumOfVoices];

private:
};

but I can't use this:

但我不能用这个:

class VoiceManager
{
public:
    const int mMaxNumOfVoices = 16;
    Voice mVoices[mMaxNumOfVoices];

private:
};

It says: "a nonstatic member reference must be relative to a specific object"

它说:“非静态成员引用必须与特定对象相关”

But in both case, mMaxNumOfVoices is a const and will be init before mVoices init (compiler follow the declaration order, no?).

但在这两种情况下,mMaxNumOfVoices都是一个const,并且在mVoices init之前是init(编译器遵循声明顺序,没有?)。

But it requires static. Why?

但它需要静态。为什么?

2 个解决方案

#1


16  

Array bounds must be known at compile-time. Though your initialisation is written there in the code, it can be overridden at runtime by a constructor. Hence your non-static member variable is not a compile-time constant.

必须在编译时知道数组边界。尽管您的初始化是在代码中编写的,但它可以在运行时由构造函数覆盖。因此,您的非静态成员变量不是编译时常量。

#2


1  

The const keyword means read-only, not constant, is like a not-be-changed promise for a specific part of the program. If you have a pointer-to-const then other parts of the program may change the value while you're not looking.

const关键字表示只读,而不是常量,就像是程序特定部分的不可更改的承诺。如果你有一个指向const的指针,那么程序的其他部分可能会在你不看时改变它。

But a static const is guaranteed that remains unchanged for the rest of the program. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration.

但是保证静态const对于程序的其余部分保持不变。程序开始时分配对象的存储空间,程序结束时分配存储空间。只存在该对象的一个​​实例。在命名空间作用域(包括全局命名空间)声明的所有对象都具有此存储持

#1


16  

Array bounds must be known at compile-time. Though your initialisation is written there in the code, it can be overridden at runtime by a constructor. Hence your non-static member variable is not a compile-time constant.

必须在编译时知道数组边界。尽管您的初始化是在代码中编写的,但它可以在运行时由构造函数覆盖。因此,您的非静态成员变量不是编译时常量。

#2


1  

The const keyword means read-only, not constant, is like a not-be-changed promise for a specific part of the program. If you have a pointer-to-const then other parts of the program may change the value while you're not looking.

const关键字表示只读,而不是常量,就像是程序特定部分的不可更改的承诺。如果你有一个指向const的指针,那么程序的其他部分可能会在你不看时改变它。

But a static const is guaranteed that remains unchanged for the rest of the program. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration.

但是保证静态const对于程序的其余部分保持不变。程序开始时分配对象的存储空间,程序结束时分配存储空间。只存在该对象的一个​​实例。在命名空间作用域(包括全局命名空间)声明的所有对象都具有此存储持