1
是否有可能通过使用typeid(TYPE).name()
来获取基地派生班级的类型名称?指向基地,转换为派生指针
静态地将基指针推回派生指针的示例。
#include <iostream>
#include <typeinfo>
class base
{
public:
virtual void known() = 0;
};
class derived: public base
{
public:
void known() { std::cout << " I guess this means "; }
void unknown(){ known(); std::cout << " its possible "; }
};
int main()
{
derived d;
std::cout << typeid(d).name() << std::endl;
// Prints out being a pointer to a derived class
base* b = &d;
std::cout << typeid(b).name() << std::endl;
// Prints out being a pointer to a base class
// But how would you use it, or in any other way,
//get the original derived type name
derived * db = (derived*) b;
// db is casted at at compile time, the derived class is known
db->unknown();
}
不'dynamic_cast'不能做? – zwol
不,这需要我确切知道派生类是什么。或者我读过它。 – Andrew
我想你想要的是[访问者模式](http://en.wikipedia.org/wiki/Visitor_pattern)? – mpark