(更新:由于问题已更改为static const
成员)
通过声明它们static const
,整数变量是安全的。在现代 C++ 中,将它们声明为static constexpr
. 语言保证您不会遇到访问未初始化(或更确切地说是零初始化)数值的问题。
对于像 double 这样的浮点数,除非您使用constexpr
. 但是,这是 C++98 中没有的功能。如果没有constexpr
,您将收到如下编译错误:
// gcc
example.cpp:6:25: error: ‘constexpr’ needed for in-class initialization of static data member ‘const double bank::BankAccount::balance’ of non-integral type [-fpermissive]
6 | static const double balance = 0.0;
| ^~~~~~~
或仅具有非标准功能:
// clang with -Wall -std=c++98
example.cpp:6:25: warning: in-class initializer for static data member of type 'const double' is a GNU extension [-Wgnu-static-float-init]
static const double balance = 0.0;
(旧答案没有声明它们const
,但让它们非常量)
你确定这个例子吗?我认为它不会编译(在 C++98 和现代 C++ 中)。除非您将初始化移出类定义,否则您将得到类似的结果:
// gcc
example.cpp:5:30: error: ISO C++ forbids in-class initialization of non-const static member ‘bank::BankAccount::account_number’
5 | static unsigned long int account_number = 123456789;
| ^~~~~~~~~~~~~~
example.cpp:6:19: error: ‘constexpr’ needed for in-class initialization of static data member ‘double bank::BankAccount::balance’ of non-integral type [-fpermissive]
6 | static double balance = 0.0;
| ^~~~~~~
// clang
example.cpp:5:30: error: non-const static data member must be initialized out of line
static unsigned long int account_number = 123456789;
^ ~~~~~~~~~
example.cpp:6:19: error: non-const static data member must be initialized out of line
static double balance = 0.0;
^ ~~~
如果您将其移出,那么您最终可能会以静态初始化顺序惨败告终。这些值将从零初始化开始,然后取决于链接器何时执行真正的初始化代码。
如果可以将变量声明为常量,那将是安全的。