c++----类型转换

目录

一、静态类型转换

二、动态类型转换

三、常量转换和重新解释转换


一、静态类型转换

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

void test01()
{
    char a = 'c';
    int b = static_cast<int>(a);
    cout << "b = " << b << endl;
}

class Base{};
class Son : public Base{};
class Other{};

void test02()
{
    Base* base = NULL;
    Son* son = NULL;
    //1、向下类型转换  不安全
    //父子之间的指针或者引用可以转换
    Son* son2 = static_cast<Son*>(base);
    //2、向上类型转换  安全
    Base* base2 = static_cast<Base*>(son);
    //3、Base*转成Other*
    //Other other = static_cast<Other>(base); //转换无效
}

int main()
{
    //test01();
    
    system("pause");
    return EXIT_SUCCESS;

}

二、动态类型转换

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

void test01()
{
    char a = 'a';
    //动态类型转换    不允许内置数据类型之间转换
    //int b = dynamic_cast<int>(a);
}
class Base { virtual void fun() {} };
class Son : public Base { void fun() {} };
class Other{};
void test02()
{
    Base* base = NULL;
    Son* son = NULL;
    //1、向下类型转换  不安全
    //Son* son2 = dynamic_cast<Son*>(base); //转换无效
    Son* son2 = dynamic_cast<Son*>(base);   //发生多态的情况是安全的
    //2、向上类型转换  安全
    Base* base2 = dynamic_cast<Base*>(son);
    //3、Base*转Other*
    //Other* other = dynamic_cast<Other*>(base);  //转换无效
}

int main()
{

    system("pause");
    return EXIT_SUCCESS;

}

三、常量转换和重新解释转换

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

void test01()
{
    //不可以将非指针或非引用做const_cast转换
    const int* p = NULL;
    int* pp = const_cast<int*>(p);

    const int* ppp = const_cast<const int*>(pp);

    //const int a = 10;
    //const int b = const_cast<int>(a);

    int num = 10;
    int& numRef = num;
    const int& num2 = const_cast<const int&>(numRef);
}

//重新解释转换    最不安全的一种转换   不建议使用
class Base{};
class Other{};
void test02()
{
    int a = 10;
    int* b = reinterpret_cast<int*>(a);

    Base* base = NULL;
    Other* other = reinterpret_cast<Other*>(base);
}

int main()
{

    system("pause");
    return EXIT_SUCCESS;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值