類型強轉(type cast)


           類型轉換有 c 風格的,當然還有 c++風格的。c 風格的轉換的格式很簡單(TYPE
EXPRESSION),但是 c 風格的類型轉換有不少的缺點,有的時候用 c 風格的轉換是不合適的,

因為它可以在任意類型之間轉換,比如你可以把一個指向 const 對象的指針轉換成指向非
const 對象的指針,把一個指向基類對象的指針轉換成指向一個派生類對象的指針,這兩種轉
換之間的差別是巨大的,但是傳統的 c 語言風格的類型轉換沒有區分這些。還有一個缺點就
是,c 風格的轉換不容易查找,他由一個括號加上一個標識符組成,而這樣的東西在 c++程
序里一大堆。所以 c++為了克服這些缺點,引進了 4 新的類型轉換操作符。

.1.靜態類型轉換:
 語法格式:
      static_cast<目標類型> (標識符)
 轉化規則:
                在一個方向上可以作隱式轉換,在另外一個方向上就可以作靜態轉換。
  int a = 10;
  int b = 3;
  cout<<static_cast<float>(a)/b<<endl; //float = int int = float
  return 0;


  int *p; void *q;
  p = static_cast<int*>(q);
  char *p = static_cast<char*>(malloc(100));

 

.2.重解釋類型轉換:
 語法格式:
               reinterpret_cast<目標類型> (標識符)
 轉化規則
            “通常為操作數的位模式提供較低層的重新解釋”也就是說將數據以二進制存在形式
的重新解釋,在雙方向上都不可以隱式類型轉換的,則需要重解釋類型轉換。

    float a = 5.6;
    int b = 5;

    b = static_cast<int>(a);
    a = static_cast<float>(b);

    void *p;int *q;
    p = q;
    //q = p ;這樣就不可以
    q = static_cast<int*>(p);

    int x = 10;
    int y = 3;
    float z = static_cast<float>(x)/y;
    cout<<z<<endl;

    //char * pc = malloc(100);編譯通不過
    char *pc = static_cast<char *>(malloc(100));

    return 0;

  .3.()常類型轉換:
 語法格式:
const_cast<目標類型> (標識符) //目標類類型只能是指針或引用
語法規則
用來移除對象的常量性(cast away the constness)使用 const_cast 去除 const 限定的
目的不是為了修改它的內容,使用 const_cast 去除 const 限定,通常是為了函數能夠接受
這個實際參數。
應用場景 1:

#include <iostream>
using namespace std;
void func(int & ref) //別人己經寫好的程序或類庫 { cout<<ref<<endl; } int main(void) { const int m = 4444; func(const_cast<int&>(m)); return 0; }
//脫掉 const 后的引用或指針可以改嗎?
int main()
{
    const int x = 200;
    int & a =const_cast<int&>(x); // int &a = x;
    a = 300;
    cout<<a<<x<<endl;
    cout<<&a<<"---"<<&x<<endl;
    int *p =const_cast<int*>(&x); // int *p = &x;
    *p = 400;
    cout<<a<<*p<<endl;
    cout<<p<<"---"<<&x<<endl;

    struct A
    {
        int data;
    };

    const A xx = {1111};
    A &a1 = const_cast< A&>(xx);
    a1.data = 222;
    cout<<a1.data<<xx.data<<endl;
    A *p1 = const_cast<A*>(&xx);
    p1->data = 333;
    cout<<p1->data<<xx.data<<endl;
    return 0;
}

  

結論:
可以改變 const 自定義類的成員變量,但是對於內置數據類型,卻表現未定義行為.
Depending on the type of the referenced object, a write operation throu
gh the resulting pointer, reference, or pointer to data member might pr
oduce undefined behavio

 

const 常變量(補充):
C++中 const 定義的變量稱為常變量。變量的形式,常量的作用,用作常量,常用於
取代#define 宏常量。

#define N 200
int main()
{
    const int a = 200;
    int b = 300;
    int c = a +b; //int c = N + b;
    cout<<c<<endl;
    return 0;
}

  


免責聲明!

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



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