RTTI(RunTime Type Information)运行时类型信息 详解
本文地址: http://blog.csdn.net/caroline_wendy/article/details/24369987
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
以上代码只是示例,
具体使用时, 避免使用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
C++ - RTTI(RunTime Type Information)运行时类型信息 详解,布布扣,bubuko.com