RTTI, RunTime Type Information, 運行時類型資訊, 是多態的主要組成部分,
通過運行時(runtime)確定使用的類型, 執行不同的函數,複用(reuse)介面.
dynamic_cast<>可以 使基類指標轉換為衍生類別的指標, 通過判斷指標的類型, 可以決定使用的函數.
typeid(), 可以判斷類型資訊, 判斷指標指向位置, 在多態中, 可以判斷基類還是衍生類別.
代碼:
/* * test.cpp * * Created on: 2014.04.22 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <typeinfo> using namespace std; class Base { public: virtual void fcnA() { std::cout << "base" << std::endl; } }; class Derived : public Base { public: virtual void fcnB() { std::cout << "derived" << std::endl; } }; void fcnC(Base* p) { Derived* dp = dynamic_cast<Derived*>(p); if (dp != NULL) dp->fcnB(); else p->fcnA(); } void fcnD(Base* p) { if (typeid(*p) == typeid(Derived)) { Derived* dp = dynamic_cast<Derived*>(p); dp->fcnB(); } else p->fcnA(); } int main(void) { Base* cp = new Derived; std::cout << typeid(cp).name() << std::endl; std::cout << typeid(*cp).name() << std::endl; std::cout << typeid(&(*cp)).name() << std::endl; fcnC(cp); fcnD(cp); Base* dp = new Base; fcnC(dp); fcnD(dp); return 0; }
輸出:
P4Base 7Derived P4Base derived derived base base
以上代碼只是樣本,
更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/
具體使用時, 避免使用dynamic_cast<>和typeid()去判斷類型, 直接通過多態即可.
注意多態的綁定只能通過指標, 如fcnC(Base*), 或引用, 如fcnD(Base&), 實現動態綁定, 兩者效果相同;
都會根據輸入的類型,動態綁定虛函數(virtual function).
代碼如下:
/* * test.cpp * * Created on: 2014.04.22 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <typeinfo> using namespace std; class Base { public: virtual void fcn() { std::cout << "base" << std::endl; } }; class Derived : public Base { public: virtual void fcn() override { std::cout << "derived" << std::endl; } }; void fcnC(Base* p) { p->fcn(); } void fcnD(Base& p) { p.fcn(); } int main(void) { Base* cp = new Derived; std::cout << typeid(cp).name() << std::endl; std::cout << typeid(*cp).name() << std::endl; fcnC(cp); fcnD(*cp); Base* dp = new Base; fcnC(dp); fcnD(*dp); Base& cr = *cp; std::cout << typeid(&cr).name() << std::endl; std::cout << typeid(cr).name() << std::endl; fcnC(&cr); fcnD(cr); Base& dr = *dp; fcnC(&dr); fcnD(dr); return 0; }
輸出:
P4Base 7Derived derived derived base base P4Base 7Derived derived derived base base
作者:csdn部落格 Spike_King