gpt4 book ai didi

c++ - 为什么不能使用 constexpr 全局变量来初始化 constexpr 引用类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:33:42 25 4
gpt4 key购买 nike

#include <iostream>
using namespace std;

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

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

最佳答案

编译时在int后加入const

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 const 值初始化对 int 变量的引用。

您可以通过使 k 成为 constint const 的引用来解决错误。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com