为什么不能使用 constexpr 全局变量来初始化 constexpr 引用类型?
Why can I not use a constexpr global variable to initialize a constexpr reference type?
#include <iostream>
using namespace std;
constexpr int r =100;
int main()
{
constexpr int &k = r ;
cout << k << endl;
}
编译此代码在编译时给出 "error: binding ‘const int’ to reference of type ‘int&’ discards qualifiers"。
编译在int
后添加const
。
constexpr int const & k = r ;
// ...........^^^^^
问题是constepxr
意味着const
,所以当你定义r
constexpr int r =100;
您将 constexpr
定义为 int const
值(还要考虑到 const
应用于左侧的类型;仅当没有在左边输入;所以 const int
和 int const
是一样的)。
但是你的k
constexpr int & k = r ;
不是 const
(由 constexpr
暗示)对 int const
的引用,而只是 const
对 int
的引用。
并且您不能使用 int const
值初始化对 int
变量的引用。
您可以通过使 k
成为 const
对 int const
的引用来解决错误。
#include <iostream>
using namespace std;
constexpr int r =100;
int main()
{
constexpr int &k = r ;
cout << k << endl;
}
编译此代码在编译时给出 "error: binding ‘const int’ to reference of type ‘int&’ discards qualifiers"。
编译在int
后添加const
。
constexpr int const & k = r ;
// ...........^^^^^
问题是constepxr
意味着const
,所以当你定义r
constexpr int r =100;
您将 constexpr
定义为 int const
值(还要考虑到 const
应用于左侧的类型;仅当没有在左边输入;所以 const int
和 int const
是一样的)。
但是你的k
constexpr int & k = r ;
不是 const
(由 constexpr
暗示)对 int const
的引用,而只是 const
对 int
的引用。
并且您不能使用 int const
值初始化对 int
变量的引用。
您可以通过使 k
成为 const
对 int const
的引用来解决错误。