之后const_cast,主函数中的值不会改变。但是当调用外部函数时发生变化,仍然在 main 中打印旧值(const int首先初始化的地方)。
int main() {
const int i = 5;
int* p = const_cast<int*>(&i);
*p = 22;
std::cout<<i;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是5,为什么?观察窗口显示的值i = 22:
那么为什么它会打印 5 呢?如果我调用外部函数,输出会有所不同:
void ChangeValue(const int i) {
int* p = const_cast<int*>(&i);
*p = 22;
std::cout<<i; //Here the value changes to 22
}
int main() {
const int i = 5;
ChangeValue(i); //Value changes to 22 in the ChangeValue function
std::cout<<i // It again prints 5. …Run Code Online (Sandbox Code Playgroud) #include <iostream>
using namespace std;
int main()
{
const int kiNum = 100;
int* ptr = const_cast<int*>(&kiNum);
*ptr = 200;
cout<<"kiNum: "<<kiNum; // The value still prints 100 on the console??
return 0;
}
output:
kiNum = 100
Run Code Online (Sandbox Code Playgroud)
在上面的代码片段中,我试图在const_cast之后更改const整数的值,然后更改地址处的值,但控制台仍然打印旧值(我使用的是visual studio 2012)