zoukankan      html  css  js  c++  java
  • c++之旅:类型的强制转换

    类型强制转换

    在编程的时候我们经常遇到类型的强制转换,C++为此提供了更安全的转换方式,在编程中我们更多的应该采用C++提供的类型转换方式

    基本类型转换

    基本类型转换用的最多,一般将高精度转换为低精度,static_cast关键字用于基本类型转换。

    float a = 1.5;
    int b =  static_cast<int>(a);
    

    上面的列子将浮点型转为整型

    常量类型转换

    常量类型转换一般将指向变量的指针强制让其指向一个常量

    const int  a = 1;
    const int* p1 = &a;
    int* p2 =  const_cast<int*>(&a);
    

    &a的返回值是const int * ,通过**const_cast强制转换为int*类型

    普通类型指针转换

    使用reinterpret_cast可以将可以实现指向普通类型的指针的类型转换

    int a = 0xA0B0C0D0;
    char* c =  reinterpret_cast<char*>(&a);
    for (int i=0; i<4; i++) {
    	printf("%x
    ", *(c+i));
    }
    

    上的示例中强制让一个char*指针指向了int型的变量,并对变量中的内容进行了访问。

    对象指针类型转换

    dynamic_csast运算符用于对象的向上转型或向下转型, 其主要用途是确保可以安全地调用虚函数。dynamic_cast的尖括号中必须为指针或者引用。如果是向下转型,其参数中的指针必须要有虚函数,如果转换失败则为NULL

    #include <iostream>
    #include <string>
    using namespace std;
    
    class Person {
        public:
            Person(){};
            virtual ~Person(){cout << "Person" << endl;}
    };
    
    class Worker: public Person {
        public:
            Worker(){};
            ~Worker(){cout << "Worker" << endl;}
    };
    
    int main(void) {
        Person* person =  dynamic_cast<Person*> (new Worker());
        Worker* worker = dynamic_cast<Worker*>(person);   //传入的person指针对应的类必须要有虚函数
        }
    

    参考

    http://www.cnblogs.com/blueoverflow/p/4712369.html

  • 相关阅读:
    使用go-fuse开发一个fuse 文件系统
    awesome-fuse-fs
    jdk 容器运行环境指定时区
    几个不错的golang工具包
    golang 一些不错的log 包
    mysql_fdw 集成go-mysql-server 开发的mysql server
    一些不错的golang web 框架
    golang gomail+fasttemplate+mailhog 发送邮件
    golang go-simple-mail+fasttemplate+mailhog 发送邮件
    实现一个简单的golang db driver
  • 原文地址:https://www.cnblogs.com/xidongyu/p/6920865.html
Copyright © 2011-2022 走看看