#include <iostream>
using namespace std;
int main() {
const int N = 22;
int * pN = const_cast<int*>(&N);
*pN = 33;
cout << N << '\t' << &N << endl;
cout << *pN << '\t' << pN << endl;
}
Run Code Online (Sandbox Code Playgroud)
22 0x22ff74
33 0x22ff74
为什么同一地址有两个不同的值?
之后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)