关于 C++ 常量性的非常简单的问题。
所以我正在读这个post ,然后我尝试了这段代码:
int some_num = 5;
const int* some_num_ptr = &some_num;
为什么编译器不给出错误或至少不给出警告?
我阅读上面声明的方式是这样说的:
Create a pointer that points to a constant integer
但是 some_num 不是常量整数——它只是一个整数。
最佳答案
问题在于您阅读代码的方式。它实际上应该读作
Create a pointer to an integer where the value cannot be modified via the pointer
C++ 中的 const int*
不保证 int
是常量。它只是一个工具,使通过指针修改原始值变得更加困难
关于C++ 常量 : how come the compiler doesn't give a warning/error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2246996/