Welcome

首页 / 软件开发 / C++ / C++:RTTI(RunTime Type Information)运行时类型信息 详解

C++:RTTI(RunTime Type Information)运行时类型信息 详解2014-11-14RTTI, 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();elsep->fcnA();}void fcnD(Base* p) {if (typeid(*p) == typeid(Derived)) {Derived* dp = dynamic_cast<Derived*>(p);dp->fcnB();} elsep->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;}
输出:

P4Base7DerivedP4Basederivedderivedbasebase
以上代码只是示例,

具体使用时, 避免使用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;}
输出:

P4Base7DerivedderivedderivedbasebaseP4Base7Derivedderivedderivedbasebase
作者:csdn博客 Spike_King