c++中,const_cast类型转换问题

#include
using namespace std;

void foo(const int a)
{
int *p = const_cast<int
>(a);
*p = 10;
cout << *a << endl; //输出10
cout << a << endl;
}
int main()
{
const int n = 100;
foo(&n);
cout << n << endl; //输出100
cout << &n << endl;//&n和foo函数中的a的值是相等的,但是对一个地址取内容为什么会不同呢?

cout << (&n) << endl; // 输出100
int *x = (int
)&n;

cout << *x << endl; //输出10 为什么?
return 0;
}

这类属于“未定义行为”,由编译器自己决定怎么实现。
可以理解为编译器在编译 cout << ncout << (&n) 的时候是直接把 n的常量值100进行输出了,而不是从n所在的地址取得值后再输出。
*p = 10是的的确确在更改n所在的地址存放的值,其它同样通过间接的地址、指针取得的值就是更改后的 10 了。
概括起来,就是编译器知道那是个常量的地方直接用了常量。

你拿int 和 int * 互相转出错很正常啊, 在64位操作系统中 一般 int 占 32位, int * 占64位, 然后就导致了地址不同

你用的是哪个编译器?
1.foo 函数要求传的参数为 const int ,而你却传了 const int* -->foo(&n);

2.const_cast 是去常转换,能这样用 int *p = const_cast(a);??

3.foo 函数当中 a 是 const int 类型,cout << *a << endl; ,*a这个操作是干嘛的?

 #include<iostream>

using namespace std;
void foo(const int *a)
{
    int *p = const_cast<int*>(a);
    *p = 10;
    cout << *a << endl; //输出10
    cout << a << endl;
}
int main()
{
    const int n = 100;
    foo(&n);
    cout << n << endl; //输出100
    cout << &n << endl;//&n和foo函数中的a的值是相等的,但是对一个地址取内容为什么会不同呢?
    cout << (&n) << endl; // 输出100
    int *x =(int*)&n;

    cout << *x << endl; //输出10 为什么?
    return 0;
}

之前代码上传的时候,出错了。源代码如上。