且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在结构/类中使用静态const int

更新时间:2023-02-05 21:36:23

C ++编译器允许静态const整数在其声明的位置指定其值。这是因为变量基本上不需要,并且只存在于代码中(它通常是编译出来的)。

C++ compilers allow static const integers (and integers only) to have their value specified at the location they are declared. This is because the variable is essentially not needed, and lives only in the code (it is typically compiled out).

其他变量类型(如static const char *)通常不能在声明的位置定义,需要单独定义。

Other variable types (such as static const char*) cannot typically be defined where they are declared, and require a separate definition.

对于一点点更多的解释,意识到访问全局变量通常需要在低级代码中进行地址引用。但是你的全局变量是一个整数,它的大小通常是地址的大小,编译器意识到它永远不会改变,所以为什么要添加指针抽象?

For a tiny bit more explanation, realize that accessing a global variable typically requires making an address reference in the lower-level code. But your global variable is an integer whose size is this typically around the size of an address, and the compiler realizes it will never change, so why bother adding the pointer abstraction?