#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
为什么同一地址有两个不同的值?
这是代码
int main()
{
const int i = 2;
const int * pi = &i;
int* j = const_cast<int *> (pi);
*j = 11;
std::cout << *pi << std::endl;
std::cout << i << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果:
11
2 <---为什么?
int main() {
const int i =10;
int *j = const_cast<int*>(&i);
cout<<endl<<"address of i "<<&i;
cout<<endl<<"value of j "<<j;
(*j)++;
cout<<endl<<"value of *j "<<*j;
cout<<endl<<"value of i "<<i;
// If Not use Const //
int k = 10;
int *p = &k;
cout<<endl<<"address of k "<<&i;
cout<<endl<<"address of p "<<&p;
(*p)++;
cout<<endl<<"value of *p "<<*p;
cout<<endl<<"value of k "<<k<<endl;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
地址
i0xbf8267d0
值j0xbf8267d0
值*j11 地址
值i10
地址k0xbf8267d0
地址p0xbf8267c8 …