c++类型转换
来源:互联网 发布:centos一键安装lamp 编辑:程序博客网 时间:2024/05/16 19:50
不同于C语言中隐式类型转换(type)expression, C++ 采用显示类型转换,有四种类型转换方式:
1. const_cast<type_id> expression ,这种方式是去除变量的常量性,
示例:
int a;
const int *b;
int *c = const_cast<int *> b;
2.static_cast<type_id> expression,这种方式执行的是静态的强制转换,包括以下几种情况
1)基本类型之间的转换,比如int到double或者相反;
2)基类和继承类之间的转换,其中基类指针转化转换为继承类型时是在编译期进行的,不执行类型安全检查,
示例:
class Base:{};
class Derived:public Base{};
Base *b = new Derived;
Derived *c = static_cast<Derived *> b;
3.dynamic_cast<type_id> expression,这种方式主要用于继承层次之间指针和引用的转换,它是在执行期进行,要进行类型安全检查
示例:
class Base:{};
class Derived:public Base{};
Base *b = new Derived;
Derived *c = dynamic_cast<Derived *> b;
Base *d = new Base;
Derived *e = static_cast<Derived *> d;//success
Derived *e = dynamic_cast<Derived *>d;//fail
4.reinterpret_cast<type_id> expression ,类似C中强制类型转换,是在二进制层面的转换,主要用于函数指针的转换,
示例:
typedef void*(funcptr)();
int * func();
int example(funcptr);
example(reinterpret_cast<funcptr>func);//从返回整数指针的类型转换成返回空指针类型的函数指针
注:
1.任何指针类型都可以转换成空指针类型;
2.继承类的层次之间,子类转换成父类是安全的;
- <C/C++> 类型转换
- C/C++:类型转换
- C类型转换
- C#.NET 类型转换
- 类型转换(C#)
- C指针类型转换
- 类型转换--c语言
- C语言类型转换
- C语言类型转换
- C/C++类型转换
- C语言类型转换
- C++_类型转换
- objective-c 类型转换
- objective-c类型转换
- 标准C 类型转换
- c类型转换
- C类型转换
- c类型转换char2short
- 代码生成器
- Windows Live Writer插件
- 安装Windows Live Writer后Ƃ
- Write your own life
- c++类型转换
- usaco 5.5 Hidden Password(最小表示法求同构)
- phpcms V9 getshell exp
- Word写论文的技
- 浏览器加载渲染网页过程解析--总结(三)
- 会生存的75条খ
- 纪晓岚妙用口
- 比尔盖茨给人
- 运行命令大全