const_cast之后的奇怪输出

问题描述

这是我的代码

#include <iostream>
using namespace std;

int main()
{
    const int a = 10;
    cout << a << endl;

    int *b = const_cast<int *>(&a);
    cout << *b << endl;
    (*b)++;
    cout << *b << endl;
    cout << a << endl;

    return 0;
}

output on ubuntu20,g++ 9.3.0
-----
10
10
11
10

输出使我感到困惑。指针b指向整数a。我已经将其转换为int *。为什么a的输出未更改而b却已更改。 const_cast工作的机制是什么。我是cpp的新手,我使用过Java。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)