【发布时间】:2015-09-27 23:38:31
【问题描述】:
据我所知,您只能在声明 if they are integral types 的同一行中初始化静态 const 成员。但是,我仍然能够初始化和使用一些静态 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,因为它在数字上是 1。正如预期的那样,Foo3 和 Foo4 甚至都没有编译。但是,我不明白为什么 Foo1 既能编译又能正常工作。是否接受此特定用法?是因为一些优化吗? (我尝试过使用 -O1 和 -O0)
注意:使用 GNU 5.2.0 和 cmake 并将标准设置为 C++98。切换到 C++11 工作正常(也就是说,不编译并要求将这些成员切换到 constexpr)。
【问题讨论】:
-
添加
-pedantic开关,那么gcc甚至会抱怨Foo1。 melpon.org/wandbox/permlink/o35cpEXlgMedfvMT
标签: c++ gcc compiler-errors