在C ++中更改静态const int的值

Fed*_*ase 1 c++ static const

我需要更改static const int成员的值。我知道这有点奇怪,但是我需要它来克服我使用的框架所赋予的限制!

我已经尝试过,但是不起作用,它会显示一个错误,提示“未定义对MyClass :: staticConstMember的引用”:

class MyClass
{
static const int staticConstMember = 10;
};
int main()
{
int* toChageValue = const_cast<int*>(&MyClass::staticConstMember);
 toChangeValue = 5;
std::cout<<MyClass::staticConstMember<<std::endl; // here I need to print 5
Return 0;
};
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 6

你不能 期。实际上用const数据类型定义的对象在C ++中是不可变的,编译器知道这一点并利用了这些知识。

您不能希望可靠地做到这一点。即使您设法以某种方式说服内存中的位实际发生了更改(使用UB,例如您尝试的强制类型转换),也无法确定编译器会从该内存中发出加载指令,而不是缓存加载结果甚至进行硬编码const对象在编译时具有的值。

更不用说这样的对象(static const int)可以驻留在程序没有写访问权的内存部分中。执行您尝试的这种不安全的转换会导致程序出现访问冲突而崩溃。

您将必须找到实现实际目标的另一种方法。