C++中四种显示类型转换总结

简介:
#include <iostream>
using  namespace  std;
 
/*
  *四种显示类型转换
  **/
 
int  main(){
 
    /* static_case 类型转换*/
     double  a=1.1213;
     int  b= static_cast < int >(a);
     class  base{};
     class  father: public  base{};
     father f;
     base ba= static_cast <base>(f);
 
     /*reinterpret_cast类型转换*/
     //基本类型的指针类型转换
     double  c=12.123;
     double * pc=&c;
     int * pi= reinterpret_cast < int *>(pc);
     //不相关的类的指针的类型转换
     class  A{};
     class  B{};
     A* pa= new  A;
     B* pb= reinterpret_cast <B*>(pa);
     delete  pa;
     //指针转换为整数
     int  num= reinterpret_cast < int >(pc);
 
     //企图转换非指针类型的
     //b=reinterpret_cast<int>(a);  这条语句是错误的
     //企图将const指针转换为void指针
//  const int * pint=0;
//  void* pvoid=reinterpret_cast<void *>(pint);   错误
     /* const_cast 类型转换*/
     const  int * pint=0;
     int  * pint1= const_cast < int  *>(pint);
     //基于安全性的考虑,下面的转换是错误的
//  const int nInt=0;
//  int nInt2=const_cast<int>(nInt);
     int * pnum=0;
     const  int  * pnum2= const_cast < const  int *>(pnum);
     int  i=0;
     //const int i2=const_cast<const int>(i); //不能编译通过
     const  int  i2=( const  int )i; //隐式转换可以编译通过
     
 
     return  0;
}

  具体的总结请参考《C++ STL开发技术导引.pdf 》第1.6小节。

目录
相关文章
|
2月前
|
设计模式 安全 算法
【C/C++ 类型转换 】深入理解C++向上转型:从基础到应用
【C/C++ 类型转换 】深入理解C++向上转型:从基础到应用
45 0
|
2月前
|
安全 编译器 程序员
特殊类设计以及C++中的类型转换
特殊类设计以及C++中的类型转换
30 2
|
2月前
|
安全 编译器 C++
【C/C++ 类型转换规则】一文了解C/C++ 中的类型转换规则,帮助你更好的编程
【C/C++ 类型转换规则】一文了解C/C++ 中的类型转换规则,帮助你更好的编程
23 0
|
5天前
|
存储 安全 编译器
C++:现代类型转换
C++:现代类型转换
23 5
|
8天前
|
编译器 C++
【C++】类与对象(static、explicit、友元、隐式类型转换、内部类、匿名对象)
【C++】类与对象(static、explicit、友元、隐式类型转换、内部类、匿名对象)
8 2
|
13天前
|
存储 编译器 C语言
【C++】C++中规范[ 类型转换标准 ] 的四种形式
【C++】C++中规范[ 类型转换标准 ] 的四种形式
|
15天前
|
安全 程序员 编译器
【C++类和对象】初始化列表与隐式类型转换
【C++类和对象】初始化列表与隐式类型转换
|
21天前
|
安全 编译器 C语言
【C++高阶(九)】C++类型转换以及IO流
【C++高阶(九)】C++类型转换以及IO流
|
2月前
|
算法 安全 编译器
【C++运算符重载】深入理解C++中的类型转换与重载
【C++运算符重载】深入理解C++中的类型转换与重载
32 0
|
2月前
|
算法 Linux 编译器
【C++ 泛型编程 进阶篇】 C++ 模版元编程 类型转换 std::decay 全面教程
【C++ 泛型编程 进阶篇】 C++ 模版元编程 类型转换 std::decay 全面教程
49 0