举例:
<span style="font-size:18px;">void main { int i = 471401; float f; f = i; //1.隐式转换 f = static_cast<float>(i); //显示转换 float ff = 12.34f; int v; v = ff; //2.隐式转换 v = static_cast<int>(ff); //显示转换 int *p = &f; //错误,编译器不允许做 int *p = (int *)&f; //正确,需要强制类型转换 int *p = static_cast<int *>(&f) //错误,强制类型转换不能用static_cast转换 }</span> 二.常量转换(const_cast) 如果从 const 转换为非 const 或从volatile(易变的)转换为非volatile的,就可以直接 使用const_cast,也是唯一允许的转换做法。举例:
<span style="font-size:18px;">void main() { const int a = 10; int *p = const_cast<int *>(&a); //将一个常量转换为非常量 const Test t; Test *pt = const_cast<Test *>(&t); volatile int k = 0; int *q = const_cast<int *>(&k); //将易变的转换为非易变的 }</span> 三.重解释转换(reinterpret_cast) 将数据从一种类型转换为完全不同另一种类型,将原有比特位根据指定类型进行改变,极不安全
举例:
<span style="font-size:18px;">void main() { int i; char *p = "This is C++!"; i = reinterpret_cast<int>(p); //将地址类型转换为整数类型 } ///class class A { private: int m; }; class B { private: int n; }; class C:public A,public B {}; void main { C c; printf("%p,%p,%p\n",&c,reinterpret_cast<B*>(&c),static_cast<B*>(&c)); }</span>reinpterpret_cast<B*>(&c)还是指向c的首地址,没有发生偏移, static_cast<B*>(&c)指向c中B的起始地址 所以,reinterpret_cast转换只是让原来数据根据指定的类型进行比特位变换,指针的位置不会发生变化 四.动态转换(dynamic_cast)
子类继承父类,将子类地址赋值给父类的指针,我们称为向上转换,不需要我们做强制转换 把父类地址赋值给子类的指针,我们称为向下转换,需要动态转换,会进行有效性检查
<span style="font-size:18px;">class Base { public: virtual void show()const { cout<<"This is Base show"<<endl; } }; clss D: public Base { void print()const { cout<<"This is D print"<<endl; } }; //RTTI 运行时的类型识别 void fun(Base *pb) { D *pd = dynamic_cast<D*>(pb); //将父类地址赋值给子类地址 } void main() { Base b; D d; fun(&b); }</span>