【发布时间】:2014-04-26 17:24:34
【问题描述】:
void main() {
const int a = 10;
const int *b = &a;
int *c = const_cast <int*>(b);
*c = 5;
cout<<a<<" "<<*b<<" "<<*c<<endl; //10 5 5
cout<<&a<<" "<<b<<" "<<c<<endl; //same address
cout<<*(int*)&a<<" "<<*&a<<endl; //5 10
}
是什么让类型转换影响了这一点? 值存储在哪里?
【问题讨论】:
-
这是
int main,而不是void main。修改常量数据是未定义的行为。不要期待任何事情。 -
const_cast仅应在您知道引用的数据不是const时使用(从不,呵呵)。 IE。如果a不是const,那么const_cast使用b指针是有价值的。正如所写,你违反了这一点。 See it live -
您的问题不清楚,因此很难确切知道您要查找的信息。
标签: c++ constants const-cast