庖丁解牛,彻底掌握c++类型转换

#include using namespace std;class Base {public:int objb;Base (int a) : objb(a){cout << "Base .... " << endl;}Base (const Base &other):objb(other.objb){cout << "Base copy ...." < (bObj);//调用转换构造函数 转换成功// B bb1 = static_cast (bObj);//编译期类型检查,所以无法成功B bb2 = reinterpret_cast (bObj);//reterinpret_cast不做任何检测,转换成功cout << "bb2.bb= " << bb2.bb << endl;//reinterpret_cast 只是把内存原模原样的复制过来cout << "&bb2=" << &bb2 << endl;cout << "&bObj=" << &bObj << endl;cout << "-------------------------------------------------" << endl;Base base1(20);Derived derived1(20,21);Base *pBase1 = &derived1;//Derived *pDerived = &base1;Derived *pDerived1 = static_cast (&base1);//父子类之间的指针转换 上行安全,下行虽不安全也可以转cout << pDerived1->objb << endl;cout << pDerived1->objd << endl;Derived* pDerived2 = reinterpret_cast (&base1);//你想干啥就干啥,安全自己负责cout << pDerived2->objb << endl;cout << pDerived2->objd << endl;//Derived* pDerived3 = dynamic_cast (&base1);//dynamic_cast 只能转换指针和引用类型,且必须polymorphic(多态,也就是虚函数)cout << "--------------------------------" << endl;virtualA va1;virtualB vb1;virtualA* pva = NULL;virtualB* pvb = NULL;pva = &va1;pvb = dynamic_cast(&va1);//继承了有虚函数的父类可以通过编译,但能否转换成功需要在运行时才知道,运行时检查不成功则返回空指针;cout << "pvb="<

你可能感兴趣的:(c/c++)