为什么我不能使用 const 更改 const 数据的值(在我的例子中为 int) const_cast

Why can't I change the value of a const data (int in my case) using const_cast

本文关键字:const 我的 int cast 不能 更改 数据 为什么      更新时间:2023-10-16

我有一个程序,如下所示:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    const int i = 100;
    cout<<"const i::"<<i<<endl;
    const_cast<int&>(i) = 200;
    cout<<"const i after cast::"<<i<<endl;
    return EXIT_SUCCESS;
}

但是i的值仍然是100。const_cast不应该改变i的值吗?

根据其定义,常量数据是常量,试图更改常量数据会导致未定义的行为

相关文章: