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