• 类型转换(静态转换: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);
  • 相关阅读:
    3.这个月有几天?
    3.这个月有几天?
    3.这个月有几天?
    2.求一个整数有几位(简单字符串操作)
    Algs4-1.2.1编写一个Point2D的用例-分治法
    Algs4-1.2.1编写一个Point2D的用例
    Algs4-1.1.39随机匹配
    Algs4-1.1.38二分查找与暴力查找
    Algs4-1.1.37糟糕的打乱
    Algs4-1.1.36乱序检查
  • 原文地址:https://www.cnblogs.com/yifengs/p/15182674.html
Copyright © 2020-2023  润新知