C++ 补充 & C++ 11 - C++ dynamic

    技术2022-07-15  81

    dynamic_cast

    动态类型转换

    将一个基类对象指针cast到继承类指针,dynamic_cast 会根据基类指针是否真正指向继承类指针来做相应处理。失败返回null,成功返回正常cast后的对象指针;

    将一个基类对象引用cast 继承类对象,dynamic_cast 会根据基类对象是否真正属于继承类来做相应处理。失败抛出异常bad_cast 注意:dynamic_cast在将父类cast到子类时,父类必须要有虚函数一起玩。

    demo 代码(一)

    #include <iostream> using namespace std; class Animal { public: virtual void cry() = 0; }; class Cat : public Animal { public: void cry() { cout << "喵喵" << endl; } void play() { cout << "爬树" << endl; } }; class Dog :public Animal { public: void cry() { cout << "旺旺" << endl; } void play() { cout << "溜达溜达" << endl; } }; void animalPlay(Animal* animal) { animal->cry(); Dog* pDog = dynamic_cast<Dog*>(animal); if (pDog) { pDog->play(); } else /* pDog == NULL */ { cout << "不是狗, 别骗我!" << endl; } Cat* pCat = dynamic_cast<Cat*>(animal); if (pCat) { pCat->play(); } else /* pDog == NULL */ { cout << "不是猫, 别骗我!" << endl; } } int main(void) { Dog* dog1 = new Dog(); Animal* a1 = dog1; //animalPlay(a1); Dog dog2; animalPlay(dog2); Cat* cat1 = new Cat(); Animal* a2 = cat1; //animalPlay(a2); Cat cat2; animalPlay(cat2); system("pause"); return 0; }

    结语:

    时间: 2020-07-02

    Processed: 0.011, SQL: 9