天天看点

const_cast的问题

CSDN上有人问到的问题:

#include <iostream>
using namespace std;

int main()
{
    const int i = 10;

    int *pi = const_cast<int *>(&i);
    ++*pi;
    cout << "  i = " << i << ", @" << &i << endl;
    cout << "*pi = " << *pi << ", @" << pi << endl;

	system("pause");
	return 0;
}
           

输出结果:

const_cast的问题

没有找到为什么,i是const int其值应该是不变的,而p是const_cast转换而来,为的是能够改变其指向的地址的值。但是这个矛盾不知道怎么解决。

转自:http://blog.csdn.net/jofranks/article/details/7828326

绝对不要去修改const变量的值,  但是这样说的话要const_cast有什么用呢?

在这里《C++Primer 第四版》中有一个例子,假设有一个函数s,他有一个唯一的参数是char*类型的,我们对他只读,不写! 在访问这个函数的时候,我们最好的选择是修改它让它接受const char*类型的参数!  但是如果不行的话 我们就要用const_cast,用一个const值调用s函数了!

[cpp]  view plain copy

  1. void s(char *)  
  2. {  
  3.     cout << 'a' << endl;  
  4. }  
  5.     char a = 's';  
  6.     const char *ss = &a;  
  7.     s(const_cast<char*> (ss));  

ok,我们编译通过了!

继续阅读