static_cast包含的转换类型有典型的非强制变换、窄化(有信息丢失)变换、使用void*的强制转换、隐式类型ios
变换、类层次的静态定位。static_cast是编译器容许的。安全
从窄类型向宽类型的转换,如char向short int,int,long int,float,double,long double的转换。spa
char a = 1; long b = static_cast<long>(a);
与第1种相反,从宽类型向窄类型的变换。指针
long b = 1; char a = static_cast<char>(b);
任何非const型指针均可以赋予void*,void*被用于对象的确切类型未知或者特定环境下对象类型发生变化的情code
况下!但void*不能直接被解除引用,由于没有类型信息可用来知道编译器怎么解释低层位模板!void*必须转换对象
成某类型的指针,在C++中没有void*到特殊类型的自动转换!必须显示强制转换!继承
struct callback_param { void *vp; }; int a = 1; struct callback_param cp; cp.vp = &a; //编译器容许从任意类型指针向void*转换 int *ip = static_cast<int *>(cp.vp);
包括(1)(2)ip
进行向上类型转换(派生类向基类转换)时,编译器清楚派生自什么祖先类,除了多继承(多继承转换后可能不为编译器
原地址,指针会在类层次中调整)。io
从const转换为非const,从volatile转换为非volatile。取得const对象的地址,会生成一个指向const的指针,
volatile同。
const int i = 0; int *ip = const_cast<int *>(&i); volatile int a = 0; int *ap = const_cast<int *>(&a);
最不安全的一种转换机制,将对象转变为彻底不一样类型的对象,这是低级的位操做。
struct msg_hdr { int msg_type; int msg_len; char msg_data[0]; }; struct msg_data { int data1; int data2; }; struct msg_hdr *p = reinterpret_cast<struct msg_hdr *>(recvbuf); struct msg_data *pdata = reinterpret_cast<struct msg_data *>(p->msg_data);
类层次的向下转换(基类向派生类转换),转换过程当中会经过RTTI检查转换类型是否正常,不正常将返回空。
#include <iostream> using namespace std; class pet{ public: virtual ~pet() { }}; class dog : public pet{}; class cat : public pet{}; int main(void){ pet *b = new cat; dog *d1 = dynamic_cast<dog *>(b); cat *d2 = dynamic_cast<cat *>(b); cout << "d1 = " << (long)d1 << endl; // d1 = 0 cout << "d2 = " << (long)d2 << endl; }
旧式强制类型能够用来替代上面的C++中新式强制类型转换,对旧式强制类型转换的支持,是为了保持向后
兼容性,以及提供与C语言兼容的符号!
格式:(expr) type 例如:
Const char* a = (const char*)b; int* b = (int*)d;