错误:无法初始化类型为'int * const'的变量,其右值为'const int *

问题描述 投票:0回答:1

为什么编译以下代码时出现此错误:error: cannot initialize a variable of type 'int *const' with an rvalue of type 'const int *?代码:

constexpr int ch1 = 5;
constexpr int* pch1 = &ch1;
constexpr int ch2 = 5;
constexpr int* pch2 = &ch2;

cout << *pch1+*pch2;

让我说清楚。整个测试过程的重点是在编译时初始化这些变量。如果有更好的方法,请告诉我。

c++ pointers constexpr
1个回答
0
投票

您已经将pch1pch2声明为constexpr的事实本身并不使它们成为const int *,因此您需要:

constexpr int ch1 = 5;
constexpr const int* pch1 = &ch1;
constexpr int ch2 = 5;
constexpr const int* pch2 = &ch2;

但是,您会得到:

error: '& ch1' is not a constant expression
error: '& ch2' is not a constant expression

所以您仍然没有赢。

Live demo

© www.soinside.com 2019 - 2024. All rights reserved.