为什么我不能使用 const 更改 const 数据的值(在我的例子中为 int) const_cast
Why can't I change the value of a const data (int in my case) using const_cast
我有一个程序,如下所示:
#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的值吗?
根据其定义,常量数据是常量,试图更改常量数据会导致未定义的行为。
相关文章:
- 为什么我的编译器在调用 const getter 函数时抛出"转换丢失(const)限定符"错误?
- 成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"
- 我应该使用 const shared_ptr<T>&or shared_ptr<T> 作为我的 lambda 函数的参数吗?
- 当我调用 main 中使用 const 对象的 const 函数时,不断出现错误
- 为什么 constexpr 假设我的方法就是 const
- 如何让我的 strchr 函数同时将'const char'数组和'char'数组作为第一个参数?
- 为什么我的运算符=(T&&)模板只绑定到一个const&而不是一个&&?
- 如何使用期望"const char*"的接口,如果我正在使用"std::byte's
- 为什么我的C 函数拒绝返回const引用
- 为什么 gcc 和 clang 为我的程序编译为不同的"const"结果?
- 我想将指向 const 对象的指针放入包含非 const 指针的容器中.我有什么选择
- 如果我返回const定义的对象,为什么const关键字被取消资格
- C++ 为什么我的覆盖代码 const int x = *(&y);工作?
- 用 C# 编组我的C++ .dll与 "const char*" 和 "const int"
- 为什么我不能用 const int 的地址初始化 int*
- 为什么不允许我将函数返回 const char* 的结果分配给 char*,bt 可以将字符串文字(常量)分配给 cha
- 为什么它不会更改我的代码中的 const 对象?
- 我只能有const重载的运算符成员函数
- 我很困惑为什么我的 fillDeck 函数说,"assigning to 'char *' from incompatible type 'const char *"
- 为什么三元操作符const我的字符串