類型轉換(靜態轉換:static_cast)


靜態轉換

  • 使用方式  static_cast< 目標類型>(原始數據)
  • 可以進行基礎數據類型轉換
  • 父與子類型轉換
  • 沒有父子關系的自定義類型不可以轉換

1.普通類型

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

//靜態轉換  static_cast<要轉成的類型>(待轉變量);
//基礎類型
void test01()
{
    char a = 'a';
    double d = static_cast<double>(a);
    cout << typeid(d).name() << endl;
}

int main()
{
    test01();
    system("Pause");
    return 0;
}

結果:

2.父子關系

取地址*轉換

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

//靜態轉換  static_cast<目標類型>(原始對象);
//1.基礎類型轉換
void test01()
{
    char a = 'a';
    double d = static_cast<double>(a);
    cout << typeid(d).name() << endl;
}
//2.父子之間轉換
class Base{};
class Child:public Base{};
class Other{};
void test02()
{
    Base* base = NULL;
    Child* child = NULL;
    //把Base轉成Child 向下轉換 不安全
    Child* c2 = static_cast<Child*>(base);

    //把Child轉成Base 向上轉型 安全
    Base* b2 = static_cast<Base*>(child);

    //轉Other類型
    Other* other = static_cast<Other*>(base); //error 類型轉換無效 因為它們沒有父子關系
}
int main()
{
    test02();
    //test01();
    system("Pause");
    return 0;
}

應用轉換

    Animal ani_ref;
    Dog dog_ref;
    //繼承關系指針轉換
    Animal& animal01 = ani_ref;
    Dog& dog01 = dog_ref;
    //子類指針轉成父類指針,安全
    Animal& animal02 = static_cast<Animal&>(dog01);
    //父類指針轉成子類指針,不安全
    Dog& dog02 = static_cast<Dog&>(animal01);

 


免責聲明!

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



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