zoukankan      html  css  js  c++  java
  • 详述C++casting操作

    Casting----类型转换,也就是将数据从一种类型转换到另一种类型的操作。本文首先给出两种类型转换的方式:隐式转换显式转换,然后简单介绍一下C语言常用的类型转换方式,最后详细叙述C++中常用的三种类型转换模版:static_cast,const_cast,reinterpret_cast

    1.隐式转换和现实转换

    隐式转换(Implict conversion):这种类型转换操作是由编译器自动完成的,程序员不需要亲自操作。

    例如:

    int iVariable = 10;
    float fVariable = iVariable; // 这里将一个整数赋值给一个浮点数,隐式触发类型转换
    

    显式转换(Explicit conversion:这种类型转换需要程序员自己显式给出类型修饰。

    例如:

    int iVariable = 20;
    float fVariable = (float) iVariable / 10;
    

    2.C++中常用三种类型转换方式

    static_cast

    用法:static_cast<type>(expression); 注:type是目标类型,expression(表达式)----可以是一个变量,或者具有计算结果的表达式

    例如:

    int iVariable = 30;
    float fVariable = static_cast<float>(iVariable); // 这一语句将类型为int的变量iVariable转换为float类型的fVariable
    

    从上面的示例代码可知,static_cast告诉编译器尝试转换两个不同类型的变量。这个转换方式常用来转换C++语言自有类型(build-in type,例如:char,int,float,double),即使类型之间会有精度的损失。此外,static_cast操作只能用在相关的指针类型之间。

    例如:

    int* pToInt = &iVariable;
    float* pToFloat = &fVariable;
    float* pResult = static_cast<float*>(pToInt); // error:不同类型的指针之间无法转换
    

    const_cast

    用法:const_cast<type>(expression); 注:type是目标类型,expression(表达式)----可以是一个变量,或者具有计算结果的表达式

    例如:

    void aFunction(int* a)
    {
    		cout << *a << endl;
    }
    
    int main()
    {
    		int a = 10;
    		const int* iVariable = &a;
    		aFunction(const_cast<int*>(iVariable));
    		// 因为函数aFunction中参数没有指定为const int*类型,那么就需要将const int*类型的变量显式的转换为非const类型
    		return 0;
    }
    

    const_cast可能是使用做少的类型转换操作,因为它不可以在不同类型之间进行转换。它仅仅是将一个const修饰的类型变量转化为非const修饰的类型变量。一般而言,我们很少使用到这个操作。

    reinterpret_cast

    用法:reinterpret_cast<type>(expression); 注:type是目标类型,expression(表达式)----可以是一个变量,或者具有计算结果的表达式

    目前来说,这是最强大的类型转换操作。reinterpret_cast实现在任意类型之间进行显式转换,也包括指针类型转换成任意其他指针类型。但是,它不能完成const_cast操作的功能。

  • 相关阅读:
    O2O、B2B、C2C(通俗讲解)
    前端 $.parseJson()
    django反向解析传参
    从url(地址栏)获取参数:Jquery中getUrlParam()方法的使用
    Django:前后端分离后联调给前端传数据
    xpath 中 [<Element a at 3985984dj343>]
    sumafan:python爬虫多线程爬取数据小练习(附答案)
    window安装mysql(详细步骤)
    sqlserver从xlsx读取数据
    第一个kotlin程序
  • 原文地址:https://www.cnblogs.com/zjz-819823900/p/14328322.html
Copyright © 2011-2022 走看看