对静态成员的常量引用
const reference to 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"|的引用。为什么?
编译器错误是标准所必需的。由于您的函数
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;
相关文章:
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 为什么我可以通过引用修改常量返回
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 将常量指针引用绑定到非常量指针
- 通过常量引用传递参数的矩阵模板类
- 按值捕获引用时出现非常量
- 在C++中使用非常量引用作为常量
- 具有常量引用参数的函数模板专用化
- 多个"常量引用"变量可以共享同一个内存吗?
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 为什么按值传递QStringView比引用常量更快?
- 通过引用常量函数调用另一个类的非常量函数
- 构造常量对象与引用常量对象
- 引用“常量value_type”时出错
- 为什么可以在 for 语句中重新分配引用常量
- 程序反馈:命名循环索引和引用常量数据
- 堆还是栈?在c++中函数调用中引用常量字符串时
- 为什么常量结构数组在按名称引用常量结构时不放在 .rodata 中?
- 为什么编译器允许在函数中发送对迭代器的引用,该函数引用常量迭代器