指向base,转换为Derived Pointer

时间:2013-12-16 03:14:56

标签: c++ oop pointers casting

是否可以使用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();
}

1 个答案:

答案 0 :(得分: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类名称。

<强>参考