如何在gdb中打印多态对象的类型

how to print ptype of polymorphic objects in gdb

考虑如下所示的简单 class:

当我们在 gdb 会话中打印 b 或 d 的 ptype 时,它​​将打印基数 class(如预期的那样)。

但逻辑上是不正确的。有什么方法可以打印对象的实际类型(基于多态行为)?

例如:-

$ ptype b

type = class Base {
  public:
    virtual void display(void) const;
}

$ ptype d

type = class Derived : public Base {
  public:
    virtual void display(void) const;
}

简单的在base中做一个函数如下

**virtual void function(){
 cout << "base class function";
}**

并在派生的 class 中使函数如下:

**void function(){
cout << "derived class";
}**

您将实现多态行为并获得正确的输出!

您可以使用 set print object on,那么您的输出将如下所示:

(gdb) set print object on 
(gdb) ptype b
type = /* real type = Base * */
class Base {
  public:
    virtual void display(void) const;
} *
(gdb) ptype d
type = /* real type = Derived * */
class Base {
  public:
    virtual void display(void) const;
} *

设置print object on后打印对象的值会发生变化,所以现在得到:

(gdb) p b
 = (Base *) 0x416eb0
(gdb) p d
 = (Derived *) 0x416ed0