BZ易风

导航

 

静态转换

  • 使用方式  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);

 

posted on 2021-08-24 21:45  BZ易风  阅读(523)  评论(0编辑  收藏  举报