#include <iostream>
using namespace std;

constexpr int r =100;
int main()
{
    constexpr int &k = r ;
    cout << k << endl;
}

编译此代码会在编译时给出“错误:将‘const int’绑定(bind)到‘int&’类型的引用丢弃限定符”。

最佳答案

编译在 const 之后添加 int

constexpr int const & k = r ;
// ...........^^^^^

问题是 constepxr 隐含 const ,所以当你定义 r
constexpr int r =100;

您将 constexpr 定义为 int const 值(还要考虑到 const 应用于左侧的类型;仅在左侧没有类型时才应用于右侧;因此 const intint const 是同一回事)。

但是你的 k
constexpr int & k = r ;

不是 const (由 constexpr 暗示)对 int const 的引用,而只是对 constint 引用。

并且您不能使用 int 值初始化对 int const 变量的引用。

您可以通过将 k 设为 constint const 的引用来解决该错误。

关于c++ - 为什么我不能使用 constexpr 全局变量来初始化 constexpr 引用类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54509583/

10-14 14:25
查看更多