为什么我不能用 const int 的地址初始化 int*
Why can't I initialize a int* with the address of a const int
这是我的:
const int x = 10;
int *ptr = &x; //error: 'initializing': cannot convert from 'const int *' to 'int *'
我知道 x
初始化后不能修改,我知道如何解决这个编译问题,但为什么我不能使用指针(在本例中为 ptr
)指向到 x
?
虽然是const int
,但我不明白为什么我不能指向它,因为我仍然可以用*ptr
来表示x
,对吧?
因为 ptr
是 int*
类型,即它指向一个非常量 int
。这允许您使用 *ptr
修改 ptr
。为防止 const
变量被修改,编译器会阻止对非常量指针的初始赋值。
将ptr
指向const int
自然会解决问题:const int* ptr = &x;
这是我的:
const int x = 10;
int *ptr = &x; //error: 'initializing': cannot convert from 'const int *' to 'int *'
我知道 x
初始化后不能修改,我知道如何解决这个编译问题,但为什么我不能使用指针(在本例中为 ptr
)指向到 x
?
虽然是const int
,但我不明白为什么我不能指向它,因为我仍然可以用*ptr
来表示x
,对吧?
因为 ptr
是 int*
类型,即它指向一个非常量 int
。这允许您使用 *ptr
修改 ptr
。为防止 const
变量被修改,编译器会阻止对非常量指针的初始赋值。
将ptr
指向const int
自然会解决问题:const int* ptr = &x;