据我所知,你只能初始化静态const成员在他们的声明if they are integral types的同一行。不过,我仍然能够初始化并使用一些静态常量双打:错误的静态const初始化,编译和工作
// compiles and works, values are indeed doubles
struct Foo1{
static const double A=2.5;
static const double B=3.2;
static const double C=1.7;
};
// compiles, but values are cast to int
struct Foo2{
static const int A=2;
static const int B=3;
static const double C=B/A; //becomes 1
};
// does not compile, Foo3::B cannot appear in a constant-expression
struct Foo3{
static const int A=2;
static const double B=3;
static const double C=A/B;
};
// does not compile, a cast to a type other than an integral or enumeration
// cannot appear in a constant-expression
struct Foo4{
static const int A=2;
static const int B=3;
static const double C=(double)A/B;
};
foo2的编译,但foo2的:: C为1,所以也许它被视为一个int,因为它是一个数字。如预期的那样,Foo3和Foo4甚至不会编译。但是,我不明白为什么Foo1编译和工作正常。这个具体用法是否被接受?是因为一些优化吗? (我试过使用-O1和-O0)
注意:使用GNU 5.2.0和cmake并将标准设置为C++ 98。切换到C++ 11可以正常工作(也就是说,不会编译并要求将这些成员切换到constexpr)。
添加'pedantic'开关,gcc甚至会抱怨'Foo1'。 http://melpon.org/wandbox/permlink/o35cpEXlgMedfvMT – dyp