【问题标题】:Strange output from typeid with RTTI of GCCtypeid 的奇怪输出与 GCC 的 RTTI
【发布时间】:2012-09-07 10:32:15
【问题描述】:

我有一些 typeid 不打印运行时对象类型的代码。代码示例是:

class interface
{
  public:
    virtual void hello()
      {
        cout << "Hello interface: " << typeid(interface).name() << endl;
      }

    virtual ~interface() {}
};

class t1 : public interface
{
  public:
    virtual void hello ()
      {
        cout << "Hello t1: " << typeid(t1).name() << endl;
      }
};

class t2 : public t1
{
  public:
    void hello ()
      {
        cout << "Hello t2: " << typeid(t2).name() << endl;
      }
};

......
  interface *p;
  t1 *p1;
  t2 *p2, *pt2;
  t3 *p3, *pt3;

  pt2 = new t2;
  std::cout << "type1: " << abi::__cxa_demangle(typeid(pt2).name(), 0, 0, &status) << "\n\n";

  p = pt2;
  assert(p != NULL);
  p->hello();
  std::cout << "type2: " << abi::__cxa_demangle(typeid(p).name(), 0, 0, &status) << "\n\n";

  p1 = dynamic_cast<t1 *>(p);
  assert(p1 != NULL);
  p1->hello();
  std::cout << "type3: " << abi::__cxa_demangle(typeid(p1).name(), 0, 0, &status) << "\n\n";

  p2 = dynamic_cast<t2 *>(p);
  assert(p2 != NULL);
  p2->hello();
  std::cout << "type4: " << abi::__cxa_demangle(typeid(p2).name(), 0, 0, &status) << "\n\n";

我使用“g++ -g -o ...”构建程序。那么输出是:

类型1:t2*

你好 t2:2t2
type2:接口*

你好 t2:2t2
type3: t1*

你好 t2:2t2
type4: t2*

打印输出似乎正确。但我希望 type2 对于 RTTI 也是 t2*。但是,输出是 interface*。我希望 type3 也是 t2*。有什么问题吗?

【问题讨论】:

    标签: g++ rtti typeid


    【解决方案1】:

    std::typeid 仅在您向其传递具有动态类型的对象时为您提供动态类型信息,但指针不被视为具有动态类型,因为它们不包含任何虚拟方法。

    所以如果你执行 std::typeid(*p) 你会得到你要找的东西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      相关资源
      最近更新 更多