C++ const_cast用法


const_cast是一種C++運算符,主要是用來去除復合類型中const和volatile屬性(沒有真正去除)。

變量本身的const屬性是不能去除的,要想修改變量的值,一般是去除指針(或引用)的const屬性,再進行間接修改。

用法:const_cast<type>(expression)

通過const_cast運算符,也只能將const type*轉換為type*,將const type&轉換為type&。

也就是說源類型和目標類型除了const屬性不同,其他地方完全相同。

 1 #include<iostream>
 2 using namespace std;
 3 void ConstTest1(){
 4     const int a = 5;
 5     int *p;
 6     p = const_cast<int*>(&a);
 7     (*p)++;
 8     cout<<a<<endl;
 9     cout<<*p<<endl;
10     
11 }
12 void ConstTest2(){
13     int i;
14     cout<<"please input a integer:";
15     cin>>i;
16     const int a = i;
17     int &r = const_cast<int &>(a);
18     r++;
19     cout<<a<<endl;
20 }
21 int main(){
22     ConstTest1();
23     ConstTest2();
24     return 0;
25 }
26 輸出:
27 5
28 6
29 若輸入7
30 則輸出8

解釋為什么輸出8:

當常變量為 const int j =i 時,直接輸出j時,編譯器不能進行優化,也就是不能夠直接用i代替j;

當常變量為const int j =5時,直接輸出j時,編譯器會進行優化,也就是用文字常量5直接代替j;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM