首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

const a,摘引变了,为啥原来常量不变

2013-04-09 
const a,引用变了,为啥原来常量不变#include iostream#include stringusing namespace stdvoid main(

const a,引用变了,为啥原来常量不变


#include <iostream>
#include <string>
using namespace std;
void main()
{
const int a=10;
 int &b=const_cast <int&>(a); //b为a的非常引用
 cout<<a<<"        "<<b<<endl;
 cout<<"&a "<<&a<<"      &b "<<&b<<endl;//ab地址相同
 b=20;
cout<<a<<"        "<<b<<endl;//ab值不同
cout<<"&a "<<&a<<"      &b "<<&b<<endl;
int *p=&b;
int *p1=const_cast<int*>(&a);
cout<<" p===   "<<p<<"  *p===  "<<*p<<endl;
cout<<" p1===   "<<p1<<"  *p1===  "<<*p1<<endl;
int const *p2=&a;
cout<<" p2===   "<<p2<<"  *p2===  "<<*p2<<endl;
int c=a;
cout<<"c==="<<c<<endl;
int const *p4=&a;
cout<<"*p4      "<<*p4<<endl;
cout<<"*&a=   "<<*(&a)<<endl;

}
const??,?改变,不变
[解决办法]
常量折叠,原因在于那个邪恶的强制转换。
[解决办法]
最好不要干这样的事,编译器喜欢规矩点的人
[解决办法]
不要纠结各种常量了,这个世界上唯一不变的就是变化。用API WriteProcessMemory还能修改正运行的其它进程的内存里面的所谓常量呢!

热点排行