2013-12-16 62 views
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(); 
} 
+0

不'dynamic_cast'不能做? – zwol

+0

不,这需要我确切知道派生类是什么。或者我读过它。 – Andrew

+0

我想你想要的是[访问者模式](http://en.wikipedia.org/wiki/Visitor_pattern)? – mpark

回答

1

鉴于其类型是一个多态基类时,typeid符的结果指的是代表最派生对象的类型std::type_info对象的表达式。

实施例:

#include <iostream> 
#include <typeinfo> 

class Base { 
    public: 

    virtual ~Base() {} 

}; // Base 

class Derived : public Base {}; 

int main() { 
    Derived derived; 
    /* By reference. */ { 
    Base &base = derived; 
    std::cout << typeid(base).name() << std::endl; 
    } 
    /* By pointer. */ { 
    Base *base = &derived; 
    std::cout << typeid(*base).name() << std::endl; 
    // NOTE: typeid(base).name() results in printing of the Base class' name. 
    } 
} 

两种情况上面打印的Derived类的名称。

参考

相关问题