对静态成员的常量引用

const reference to static member

本文关键字:引用 常量 静态成员      更新时间:2023-10-16
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"|的引用。为什么?

编译器错误是标准所必需的。由于您的函数

void f(const int& x)

在调用中通过引用获取参数

f(Foo::n);

变量Foo::n使用 ODR 的。因此需要一个定义

有 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++11方言方面存在一些问题(ideone.com 编译了100%的成功)。

也许,尝试一下是个好主意?

struct Foo
{
    static int n;
};
int Foo::n = 10;