C++类型转换

来源:互联网 发布:网络贷款有风险 编辑:程序博客网 时间:2024/06/05 22:04
//类型转换;//在C语言中有两种转换方式:隐式转换,显示转换(强制类型转换);/*//强制类型转换;double f = 1.2f;int n = (int)f;char* p = (char*)malloc(1024);//malloc一般返回的是void*类型;*///C++的类型转换;/*常见的几种方式;1、静态类型转换:static_cast<类型>(变量);需要编译器对类型转换安全性进行检查,或者将void* 转换成具体类型的指针;任何类型的指针都可以通过隐式类型转换转成void*,但是void*转换成其它类型时需要显示转换;静态转换是编译器在编译时就已经确定的,由编译器去完成;*//*#include <iostream>using namespace std;void main(void){double f = 1.2f;int n = static_cast<int>(f);cout<<f<<endl;cout<<n<<endl;char* p = "hello";//n = static_cast<int>(p);//编译错误;//n = (int)p;//不报错;//cout<<"ERROR: "<<n<<endl;system("pause");return ;}//这样可以避免失误造成的错误,编译器如果发现类型转换有风险,就会报错提示;//静态类型转换的成功条件是:在源类型和目标类型之间,只要有一个方向上可以做隐式类型转换,那么两个方向上就都可以做静态类型转换;*//*2、动态类型转换:dynamic_cast<类型>(变量);用于在具有多态特性的父子类之间的转换;(未完待续,以后再补充)*//*3、常量类型转换:const_cast<类型>(变量);用于去除指针或者引用上的const属性;const指针或引用的意义在于他所指向的内容是不能被修改的;而常量类型转换是把不能被修改的转换为可以被修改的;*//*#include <iostream>using namespace std;void main(void){const int cn = 5;//cn = 10;//报错,常量是不能赋值的;//尝试用地址的方式修改;int* pn = const_cast<int*>(&cn);//cn的地址是const int*,需要去掉const属性;*pn = 20;cout<<cn<<endl<<*pn<<endl;//5,20;system("pause");return ;}//执行发现cn的值并没有改变,因为编译器在编译时,会把const类型的目标从内存移动到寄存器中;//所以当我们通过地址修改值时,只是修改了内存中的值,并没有访问寄存器中的值,所以cn的值不会改变;//如果强制修改寄存中的const值,可以使用volatile关键字,目的是不让编译器进行内存优化。告诉编译器,这个值是易失的,易变的;const volatile int cn = 5;//关闭寄存器优化;*//*4、重解释类型转换:reinterpret_cast<类型>(变量);允许对任意类型的指针进行转换;不会对类型相容性进行检查,只是对两个变量之间进行赋值;用于在指针和其它类型之间进行转换;*//*#include <iostream>#include <fstream>#include <cstdio>using namespace std;struct Person{char name[128];int age;};void main(void){char* p = "hello";int n = reinterpret_cast<int>(p);cout<<p<<endl<<n<<endl;double * pf = reinterpret_cast<double*>(p);cout<<pf<<endl;//例如查看一个指针的值;printf("%p\n",p);//十进制显示;printf("%d\n",p);//做了一个类型转换;cout<<endl<<endl<<endl;Person boy = {"Simon",25};ofstream ofs ("T.dat");//.dat是一个二进制文件;(未完待续,以后补充)ofs.write(reinterpret_cast<char*>(&boy),sizeof(boy));ofs.close();//例如用于从服务器接受数据包并解析;char* data = "20150628";struct Date{char year[4];char month[2];char day[2];};Date* today = reinterpret_cast<Date*>(data);cout<<today->year<<"-"<<today->month<<"-"<<today->day<<endl;// 20150628-0628-28因为结构体开辟的是一块连续的空间,虽然按照定义的字符数组大小截取字符,但值是上一次截取后的剩余值;system("pause");return ;}*/


 关于reinterpret_cast 可以参考

http://www.cnblogs.com/ider/archive/2011/07/30/cpp_cast_operator_part3.html

 

0 0