C++的类型转换

1 类型转换名称和语法

C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是:

TYPE b = (TYPE)a

C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。

    static_cast        静态类型转换。如int转换成char

        reinterpreter_cast    重新解释类型

      dynamic_cast        命名上理解是动态类型转换。如子类和父类之间的多态类型转换。

const_cast,        字面上理解就是去const属性。

4种类型转换的格式:

    TYPE B = static_cast<TYPE> (a)

2 类型转换一般性介绍

    1)static_cast<>()    静态类型转换,编译的时c++编译器会做类型检查;

基本类型能转换 但是不能转换指针类型

    2)若不同类型之间,进行强制类型转换,用reinterpret_cast<>() 进行重新解释

    3)一般性结论:

C语言中 能隐式类型转换的,在c++中可用 static_cast<>()进行类型转换。因C++编译器在编译检查一般都能通过;

C语言中不能隐式类型转换的,在c++中可以用 reinterpret_cast<>() 进行强行类型 解释。总结:static_cast<>()和reinterpret_cast<>() 基本上把C语言中的 强制类型转换给覆盖

reinterpret_cast<>()很难保证移植性。

    4)dynamic_cast<>(),动态类型转换,安全的基类和子类之间转换;运行时类型检查

    5)const_cast<>(),去除变量的只读属性    

3 典型案例

3.1 static_cast用法和reinterpret_cast用法

 

void main01()

{

    double dPi = 3.1415926;

 

    //1静态的类型转换: 在编译的时 进行基本类型的转换 能替代c风格的类型转换 可以进行一部分检查

    int num1 = static_cast<int> (dPi); //c++的新式的类型转换运算符

    int num2 = (int)dPi;                //c语言的 旧式类型转换

    int num3 = dPi;                        //隐士类型转换

    cout << "num1:" << num1 << " num2:" << num2 << " num3:" << num3 << endl;

 

 

    char *p1 = "hello wangbaoming ";

    int *p2 = NULL;

    p2 = (int *)p1;

 

    //2 基本类型能转换 但是不能转换指针类型

    //p2 = static_cast<int *> (p1); //"static_cast": 无法从"char *"转换为"int *"

 

    //3 可以使用 reinterpret_cast 进行重新解释

    p2 = reinterpret_cast<int *> (p1);

    cout << "p1 " << p1 << endl;

    cout << "p2 " << p2 << endl;

 

    //4 一般性的结论:    c语言中 能隐式类型转换的 在c++中可以用 static_cast<>()进行类型转换 //C++编译器在编译检查一般都能通过

    //c语言中不能隐式类型转换的,在c++中可以用 reinterpret_cast<>() 进行强行类型 解释

 

    system("pause");

    return;

}

 

3.2 dynamic_cast用法和reinterpret_cast用法

 

class
Animal

{

public:

    virtual
void cry() = 0;

};

 

class
Dog : public
Animal

{

public:

    virtual
void cry()

    {

        cout << "wangwang " << endl;

    }

 

    void doSwim()

    {

        cout << "我要狗爬" << endl;

    }

};

 

 

class
Cat : public
Animal

{

public:

    virtual
void cry()

    {

        cout << "miaomiao " << endl;

    }

    void doTree()

    {

        cout << "我要爬树" << endl;

    }

 

};

 

class
Book

{

public:

    void printP()

    {

        cout << price << endl;

    }

 

private:

    int price;

 

};

 

void ObjPlay(Animal *base)

{

    base->cry();

    Dog *pDog = dynamic_cast<Dog *>(base);

    if (pDog != NULL)

    {

        pDog->cry();

        pDog->doSwim();

    }

 

    Cat *pCat = dynamic_cast<Cat *>(base);

    if (pCat != NULL)

    {

        pCat->cry();

        pCat->doTree();

    }

}

void main02()

{

    Animal *base = NULL;

 

    //1 可以把子类指针赋给 父类指针 但是反过来是不可以的 需要 如下转换

    //pdog = base;

    Dog *pDog = static_cast<Dog *> (base);

 

    //2 把base转换成其他 非动物相关的 err

    //Book *book= static_cast<Book *> (base);

 

    //3 reinterpret_cast //可以强制类型转换

    Book *book2 = reinterpret_cast<Book *> (base);

 

    //4 dynamic_cast用法

    ObjPlay(new
Cat());

 

    system("pause");

}

 

3.3 const_cast用法

 

//典型用法 把形参的只读属性去掉

void Opbuf(const
char *p)

{

    cout << p << endl;

    char *p2 = const_cast<char*>(p);

    p2[0] = 'b';

    cout << p << endl;

}

 

void main()

{

    const
char *p1 = "11111111111";

 

    char *p2 = "22222222";

 

    char *p3 = const_cast<char *>(p1);

    char buf[100] = "aaaaaaaaaaaa";

 

    Opbuf(buf);

 

    //要保证指针所执行的内存空间能修改才行 若不能修改 还是会引起程序异常

    //Opbuf("dddddddddddsssssssssssssss");

 

    system("pause");

}

4 总结

结论1:程序员要清除的知道: 要转的变量,类型转换前是什么类型,类型转换后是什么类型。转换后有什么后果。

结论2:一般情况下,不建议进行类型转换;避免进行类型转换。

C++复习:C++的类型转换的更多相关文章

  1. python8--文件操作 with。。。open语法

    复习   一.类型转换 1.数字类型:int() | bool() | float()  2.str与int:int('10') | int('-10') | int('0') | float('-. ...

  2. C++_day8_ 多重继承、钻石继承和虚继承

    1.继承的复习 1.1 类型转换 编译器认为访问范围缩小是安全的. 1.2 子类的构造与析构 子类中对基类构造函数初始化只能写在初始化表里,不能写在函数体中. 阻断继承. 1.3 子类的拷贝构造与拷贝 ...

  3. Java连载67-深入一维数组、main方法中的args参数详解

    一.复习了一维数组,还复习了强制类型转换的注意点. package com.bjpowernode.java_learning; public class D67_1_GoDeepIntoArrays ...

  4. ndk学习之c++语言基础复习----C++容器、类型转换、异常与文件流操作

    继续来复习C++,比较枯燥,但是这是扎实掌握NDK开发的必经之路,不容小觑. 容器: 容器,就是用来存放东西的盒子. 常用的数据结构包括:数组array, 链表list, 树tree, 栈stack, ...

  5. 项目期复习:JS操作符,弹窗与调试,凝视,数据类型转换

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/huangyibin628/article/details/26364901 1.JS操作符 ① 除法 ...

  6. Java基础复习之一篇:关健字,标识符,注释,常量,进制转换,变量,数据类型,数据类型转换

    1.关健字 1.1.被Java语言赋予特定意义的单词(如:class,interface,public ,static) 1.2.全部是小写 1.3.注意事项(goto和const作为关健字保留起来) ...

  7. C#复习④

    C#复习④ 2016年6月16日 12:37 Main Classes and Structs 类和结构体 1.Contents of Classes 字段,常量,方法,构造函数,析构函数: 特性,事 ...

  8. C#复习③

    C#复习③ 2016年6月16日 11:13 Main Declaration & Statement 声明和语句 1.一个程序包含的声明空间有哪些? Namespace : declarat ...

  9. C#复习②

    C#复习② 2016年6月15日 09:08 1.C#之Symbols Identifier = (letter|'_'|'@'){letter|digit|'_'}. 需要注意: 1.Unicode ...

随机推荐

  1. 1125 Chain the Ropes (25 分)

    1125 Chain the Ropes (25 分) Given some segments of rope, you are supposed to chain them into one rop ...

  2. 保存chrome主题背景的图片

    chrome主题背景的图怎样可以保存下来? 在chrome地址栏中输入: chrome://theme/IDR_THEME_NTP_BACKGROUND?npebkpkiddfadallfhefpip ...

  3. linux系统添加指定uid和gid的用户和组

    1.添加指定gid的组 groupadd -g 1001 upload # 添加了一个指定gid为1001的upload用户 2.添加指定uid的用户,并加入到指定组 useradd -u 1001 ...

  4. Memory Translation and Segmentation.内存地址转换与分段

    原文标题:Memory Translation and Segmentation 原文地址:http://duartes.org/gustavo/blog/ [注:本人水平有限,只好挑一些国外高手的精 ...

  5. ViewPager的addOnPageChangeListener和setOnPageChangeListener的区别,ViewPager改变数据后IndexOutOfBoundsException

    我的ViewPager数据改变后,在切换界面刷新数据时:OnPageChangeListener中的数据IndexOutOfBoundsException,我们来看源码探一下究竟: 代码时这样写的: ...

  6. RecyclerView中设置match_parent无效;

    在RecyclerView中宽度设置了match_parent,但是效果和wrap_content一样: 说下解决方法: 1.这样子写,match_parent没有效果: View v = View. ...

  7. 打jar包的几种方式

    测试用类public class Hello {    public static void main(String[] args) {        System.out.println(" ...

  8. MySQL关于sql_mode的修改(timestamp的默认值不正确)

    timestamp的默认值不正确原因: MySQL5.7版本中有了一个STRICT mode(严格模式),而在此模式下默认是不允许设置日期的值为全0值的,所以想要解决这个问题,就需要修改sql_mod ...

  9. 【Git使用】sourcetree跳过注册的方法(转)

    当前只有Win的版本,Mac自行百度(笑) 很多人用git命令行不熟练,那么可以尝试使用sourcetree进行操作. 然鹅~~sourcetree又一个比较严肃的问题就是,很多人不会跳过注册或者操作 ...

  10. C#取整函数Math.Round、Math.Ceiling和Math.Floor

    1.Math.Round:四舍六入五取偶 引用内容 Math.Round(0.0) //0Math.Round(0.1) //0Math.Round(0.2) //0Math.Round(0.3) / ...