c++ - 对静态成员的 const 引用

标签 c++ c++11 reference static member

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::nodr-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/

相关文章:

c++ - 使用 unique_ptr 离开范围时堆损坏

c++ - 后期不可复制成员初始化

c++ - 将引用的结构/类引用传递给函数

php - 为什么不能用三元运算符选择引用?

c++ - Hessian 最小阈值对 SurfFeatureDetector 函数意味着什么?

c++ - 对象在超出范围时被解构

带有 unique_ptr 的 C++ 嵌套映射

c++ - 发出 std::async 任务完成的信号

c++ - 如何在 rstudio 上为使用子目录内 src 文件夹中的 C/C++ 文件的包构建和加载共享库?

c++ - 指向整数数组的指针 C++