轉載:https://blog.csdn.net/gaojing303504/article/details/78860773ios
dynamic_cast運算符的主要用途:將基類的指針或引用安全地轉換成派生類的指針或引用,安全
並用派生類的指針或引用調用非虛函數。若是是基類指針或引用調用的是虛函數無需轉換就能在運行時調用派生類的虛函數。函數
前提條件:當咱們將dynamic_cast用於某種類型的指針或引用時,只有該類型至少含有虛函數時(最簡單是基類析構函數爲虛函數),才能進行這種轉換。不然,編譯器會報錯。spa
用個例子來講明:.net
1.基類中沒有虛函數:指針
#ifndef _CLASS_H_ #define _CLASS_H_ class Base { public: Base(); ~Base(); void print(); }; class Inherit :public Base { public: Inherit(); ~Inherit(); void show(); }; #endif
#include "Class.h" #include <iostream> Base::Base() { } Base::~Base() { } void Base::print() { std::cout << "Base funtion" << std::endl; } Inherit::Inherit() { } Inherit::~Inherit() { } void Inherit::show() { std::cout << "Inherit funtion" << std::endl; }
#include "Class.h" int main() { Base* pbase = new Inherit(); Inherit* pInherit = dynamic_cast<Inherit*>(pbase); return 0; }
編譯器報錯:code
咱們改基類blog
class Base { public: Base(); virtual ~Base(); void print(); };
#include "Class.h" int main() { Base* pbase = new Inherit(); Inherit* pInherit = dynamic_cast<Inherit*>(pbase); pInherit->show();//這樣動態轉換,咱們就能夠調用派生類的函數了 return 0; }