const_cast

函數原型express

const_cast < type-id > ( expression )

  去掉const屬性:const_cast<int*> (&num),經常使用,由於不能把一個const變量直接賦給一個非const變量,必需要轉換。函數

  加上const屬性:const int* k = const_cast<const int*>(j),通常不多用,由於能夠把一個非const變量直接賦給一個const變量,好比:const int* k = j;spa

1.常量指針被轉化成很是量指針,轉換後指針指向原來的變量(即轉換後的指針地址不變)

class A 
{ 
  public: 
    A() 
    { 
      m_iNum = 0; 
    } 

   public: 
    int m_iNum; 
}; 

void foo() 
{ 
    //1. 指針指向類 
  const A *pca1 = new A; 
  A *pa2 = const_cast<A*>(pca1); //常量對象轉換爲很是量對象 
  pa2->m_iNum = 200; //fine 

  //轉換後指針指向原來的對象 
  cout<< pca1->m_iNum <<pa2->m_iNum<<endl; //200 200 
  
  //2. 指針指向基本類型 
  const int ica = 100; 
  int * ia = const_cast<int *>(&ica); 
  *ia = 200; 
  cout<< *ia <<ica<<endl; //200 100 
}

2.常量引用轉爲很是量引用

class A 
{ 
    public: 
      A() 
      { 
            m_iNum = 1; 
      }     
    public: 
      int m_iNum; 
}; 

void foo() 
{ 

  A a0; 
  const A &a1 = a0; 
  A a2 = const_cast<A&>(a1); //常量引用轉爲很是量引用 

  a2.m_iNum = 200; //fine 

  cout<< a0.m_iNum << a1.m_iNum << a2.m_iNum << endl; //1 1 200 
}

3.常量對象(或基本類型)不能夠被轉換成很是量對象(或基本類型)

void foo() 
{ 
  //常量對象被轉換成很是量對象時出錯 
  const A ca; 
  A a = const_cast<A>(ca); //不容許 
  
  const int i = 100; 
  int j = const_cast<int>(i); //不容許 

}

  這種轉換隻是開了一個接口,並非實質上的轉換。(其實也算是實質上的轉換了,只不過表達上不容許這樣寫).net

4.添加const屬性

int main() 
{ 
  int i = 100; 
  int *j = &i; 
  const int *k = const_cast<const int*>(j); 
  //const int *m = j; 感受和這樣寫差很少 

  //指的地址都同樣 
  cout <<i<<","<<&i<<endl; //100, 0012FF78 
  cout <<*j<<","<<j<<endl; //100, 0012FF78 
  cout <<*k<<","<<k<<endl; //100, 0012FF78 

  *j = 200; 
  //*k = 200; //error 

  return 0; 
}

總結

1. 使用const_cast去掉const屬性,其實並非真的改變原類類型(或基本類型)的const屬性,它只是又提供了一個接口(指針或引用),使你能夠經過這個接口來改變類型的值。也許這也是const_cast只能轉換指針或引用的一個緣由吧。指針

2. 使用const_cast添加const屬性,也是提供了一個接口,來不讓修改其值,不過這個添加const的操做沒有什麼實際的用途。code

 https://blog.csdn.net/qq_26849233/article/details/62218385對象

本站公眾號
   歡迎關注本站公眾號,獲取更多信息