struct Foo
{
constexpr static int n = 10;
};
void f(const int &x) {}
int main()
{
Foo foo;
f(Foo::n);
return 0;
}
我收到错误:main.cpp|11|对 `Foo::n'| 的 undefined reference 。为什么?
最佳答案
编译错误是标准要求的。由于你的功能
void f(const int& x)
在调用中通过引用获取它
f(Foo::n);
变量 Foo::n
是 odr-used。因此需要定义。
有2种解决方案。
1 定义Foo::n
:
struct Foo
{
constexpr static int n = 10; // only a declaration
};
constexpr int Foo::n; // definition
2 按值取 f
的参数:
void f(int x);
关于c++ - 对静态成员的 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18759471/