【问题标题】:Print all inherited class member variables and methods打印所有继承的类成员变量和方法
【发布时间】:2020-10-18 19:05:50
【问题描述】:

假设我有如下继承:

class A
{
public:
A(){}
int s;
void Show(){}
};

class B : public A
{
public:
B(){}
int y;
void MyShow() {}
};

int main()
{
B b;
}

有没有一种方法可以让我通过任何机制 [运行时/调试] 等知道对象 b 的成员变量/方法是什么 - 我的意思是完整列表以及它继承的所有内容?

【问题讨论】:

  • 没有直接的办法。您可以将对象序列化为具有完整信息的文件。然后调查一下。

标签: c++ c++11 gcc visual-c++ gdb


【解决方案1】:

你不能那样做。 C++ 不支持反射(您需要能够执行此操作的功能)。您不能像在某些其他(动态)语言中那样遍历对象并发现其成员。

【讨论】:

    【解决方案2】:

    您可以使用ptype gdb 命令。但是它不会打印继承类型的成员,您必须自己做。这里可以打印B,注意它继承自A,也可以打印A

    (gdb) ptype B
    type = class B : public A {
      public:
        int y;
    
        B(void);
        void MyShow(void);
    }
    (gdb) ptype A
    type = class A {
      public:
        int s;
    
        A(void);
        void Show(void);
    }
    (gdb) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2012-05-16
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多