天天看點

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,我們編譯通過了!

繼續閱讀