为什么 int *const p1;在 int *p1; 工作正常时导致错误?

Why int *const p1; results in error while int *p1;works just fine?

我是 C++ 的新手,正在尝试学习指针的概念。我很困惑为什么第三个和第四个语句会导致错误,而第一个和第二个语句运行正常。

int *p1; //Ok
const int *p1;//Ok
int *const p1; //error: default initialization of an object of const type 'int *const'
const int *const p1; //error: default initialization of an object of const type 'const int *const'

PS:我知道在声明它们时初始化所有指针或至少将它们的值设置为 nullptr 或 0 是一种很好的做法。我问这个问题是因为我想了解它背后的概念。

最后两个语句将指针本身声明为常量。你没有给他们价值观。这使得它们非常无用,因为它们永远无法更改(如果它们是堆栈或 class 成员变量,它们甚至没有像 NULL 这样的定义值,所以它们实际上是没用)。

Non-class 具有 top-level const 的类型必须在定义中初始化。

第3、4行有top-levelconst,意思是p1不能修改。第2行没有top-levelconstp1 可以修改,但它指向的int不能修改。

这不是良好做法的问题。
您正在声明几个指向 int 和 const int 的 const 指针(有关详细信息,请参阅 here),在这两种情况下,您都必须在定义它们时对其进行初始化。