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.继承类的层次之间,子类转换成父类是安全的;
 
 
 

 

原创粉丝点击