栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

(C++)类型转换

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

(C++)类型转换

目录

1、类型转换概念

2、static_cast

3、reinterpret_cast

4、const_cast

5、dynamic_cast


1、类型转换概念

C语言类型转换:

1.过于粗暴

任意类型之间都能进行转换,编译器很难判断其正确性

2.难于定义

在源码中很难查看使用强制类型转换的语句

2、static_cast

//用于基本类型之间的转换,但是不能用于基本类型指针之间的转换

//用于有继承关系对象之间的转换和类指针之间的转换

//static_cast是在编译期间转换的,无法在运行时检测类型,所以类型之间的转换有可能存在风险

#include 
using namespace std;

class Parent
{


};
class Child:public Parent
{


};
int main(int argc, char const *argv[])
{
    int a = 1;
    char ch = 'a';
    a = static_cast(ch);   //用于普通类型之间的转换
    //int *p = static_cast(&ch);   //不能用于普通类型指针之间的转换

    Parent p;
    Child c;
    p = static_cast(c);  //用于有继承关系的对象之间的转换

    Parent *p1 = static_cast(&c);  //用于类对象指针之间的转换
    return 0;
}

3、reinterpret_cast

reinterpret_cast:

1.用于普通类型指针之间的转换

2.用于数字和指针之间的转换(容易出现野指针)

#include 
using namespace std;


int main(int argc, char const *argv[])
{
    int b = 10,a = 100;
    char *p = reinterpret_cast(&a);   //用于普通类型指针之间的转换(不安全)
    cout<<*(p + 1)<(100);  //用于数字和指针之间的转换
    *q = 1;                                 //(很容易出现野指针)
    return 0;
}

4、const_cast

常量或常引用的转换

#include 
using namespace std;

int main(int argc, char const *argv[])
{
    const int a = 1;                   //C++中常量不可以改变
    int *p = const_cast(&a);
    *p = 100;
    cout<(m);
    n = 100;
    cout<(x);
    y = 100;
    cout< 

5、dynamic_cast

派生类与基类之间的转换

//运行时进行参数类型的检查,如果不能转换,会返回NULL,比static_cast 安全

#include 
using namespace std;
class Parent
{
    public:
        virtual void show(){}
};
class Child:public Parent
{
    public:
    virtual void show(){}
};
int main(int argc, char const *argv[])
{
    Child *c = new Child;
    delete c;
    //c = static_cast(new Parent);   //派生类指针指向基类对象


    c = dynamic_cast(new Parent);  //运行的时候进行参数类型的检查,如果不能转换,会返回NULL,比static_cast安全
    if(c == NULL)
    {
        cout<<"转换失败"<

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938342.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号