当一个常量取其他常量值时,C++常量初始化

Ben*_*nas 0 c++ initialization constants

我无法在类中初始化常量,其中一个常量依赖于其他常量值.

class foo {
private:
   const int secondConst;
   const int firstConst;
public:
   foo(int x) :
          firstConst(x),
          secondConst(firstConst*3)
   {
       // constructor code here....
   }
}
Run Code Online (Sandbox Code Playgroud)

secondConst是一个垃圾值,我该如何正确初始化它?也许在C++中,一个常量在初始化时不能依赖其他常量?

我编辑了我的帖子.问题实际上是在原始代码中我切换了声明它们的const字段.

Ale*_*exD 5

你的样本适合我.但是,如果我改变订单

private:
   const int secondConst;
   const int firstConst;
Run Code Online (Sandbox Code Playgroud)

然后secondConst得到垃圾.原因是数据成员按声明的顺序初始化,而不是按成员初始化列表中出现的顺序初始化.

从标准:

然后,非静态数据成员按照它们在类定义中声明的顺序进行初始化(同样不管mem-initializers的顺序如何).