classDerived : public Base { public: Derived() :_j(1) { ; } virtualvoidT(){ cout << "Derived:T" << _j << endl; }
private: int _j; };
intmain() { // static_cast int i = 6; double d = static_cast<double>(i); //基本类型转换 int -> double double d2 = 5.6; int i2 = static_cast<int>(d2); //基本类型转换 double -> int
int ii = 5; double dd = static_cast<double>(ii); double dd2 = 5.6; int ii2 = static_cast<int>(dd2);
// static_cast与dynamic_cast
Base cb; Derived cd; Base* pcb; Derived* pcd;
// 子类--》 父类 // 这个是安全的 pcb = static_cast<Base*>(&cd); if (pcb == NULL) { cout << "unsafe static_cast from Derived to Base" << endl; } pcb = dynamic_cast<Base*>(&cd); if (pcb == NULL) { cout << "unsafe dynamic_cast from Derived to Base" << endl; }
// 父类--》 子类 // 这个有风险,dynamic_cast会做检查导致失败 pcd = static_cast<Derived*>(&cb); if (pcd == NULL) { cout << "unsafe static_cast from Base to Derived" << endl; } pcd = dynamic_cast<Derived*>(&cb); if (pcd== NULL) { cout << "unsafe dynamic_cast from Base to Derived" << endl; }