考虑以下代码:
静态成员的定义与类内声明不同,即使用
#include <iostream>
struct Foo
{
constexpr static int n = 42;
};
const int Foo::n; // note const, NOT constexpr
int main()
{
std::cout << Foo::n;
}
静态成员的定义与类内声明不同,即使用
const
而不是 constexpr
。上面的代码是否合法?如果合法,为什么?它可以在 gcc 和 clang 中编译。如果我们在定义中交换 const
和声明中的 constexpr
,它也可以编译。我知道 constexpr
对变量意味着 const
,但反之则不然。