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
作者:csdn博客 Spike_King