【发布时间】:2014-02-25 22:02:38
【问题描述】:
对于下面的代码,为什么 main 中的第一种情况在没有重新声明 Foo::bar 的情况下可以正常工作,而函数的第二种情况需要它?
struct Foo{
static constexpr int bar = 30;
};
//Declaration of Foo::bar outside of struct
constexpr int Foo::bar;
int returnconstexpr(const int& x) { return x; }
int main()
{
//Ok without declaration outside of struct
std::cout << Foo::bar << std::endl;
//Requires declaration outside of struct
std::cout << returnconstexpr(Foo::bar) << std::endl;
//Here static constexpr works as a definition
static constexpr int x = 2;
std::cout << returnconstexpr(x) << std::endl;
return 0;
}
我假设这是因为在第一种情况下,编译器实际上只是保留了值,而在第二种情况下,函数需要一个在没有重新声明的情况下尚不存在的地址。如果是这样,那么我所说的是声明实际上是一个定义吗?我对此感到困惑,因为在类中提供了一个初始化程序,但它并没有使它成为一个定义。例如,第三种情况就可以了。
【问题讨论】:
标签: c++ struct static definition constexpr