如何找出正在处理的派生类

How to find out which derived class is processing

本文关键字:派生 处理 何找出      更新时间:2023-10-16

我有一个 BaseInterface 类,其中包含一个虚拟的 void execute() 由派生类实现:

class BaseInterface
{
public:
    virtual void execute(int a) = 0;
}

我有大量的派生类覆盖了执行空:

class ProcessN : public BaseInterface
{
public:
    void execute(int a);
}

执行我的一个派生类的无效有一个错误。但是有大量的派生类。很难一一检查它们中的每一个。我很难找到错误。

C++中是否有一种方法可以通过基类找出当前正在处理哪个派生类?

编辑:好的,在对评论进行有用的讨论后,我改进了我的问题:

我可以在 BaseInterface 类的构造函数中实现一些东西,以打印出当前处理派生类的信息吗?

您正在寻找类型ID

BaseInterface *a = new Process1();
BaseInterface *b = new Process2();
cout << typeid(*a).name() << endl;
cout << typeid(*b).name() << endl;

或者如果你想在你的 execute() 中使用,你可以简单地使用 typeid(*this)

class BaseInterface
{
public:
    virtual void execute(int a) = 0;
    //debug helper
    void print_info() { cout << typeid(*this).name() << endl; }
};
class ProcessN : public BaseInterface
{
    void execute(int a) { print_info(); }
};

如何调用执行....也许您可以在基类中引入一个静态方法,该方法将基类指针作为参数,并在执行之前调用此方法,并使用 BasePointer 从此方法中的派生对象打印必要的信息,以查看它是哪个派生类对象。根据我的理解,我建议如下。如果它没有帮助,那就最好了。

class Base
{
   public:
   virtual void exec(int i) =0 ;
   static void check(Base* temp)
   {
     cout<<"Type of obj"<<typeid(*temp).name()<<endl;
    }
 };
class Derived1 : public Base
{
 public:
 void exec(int i)
 {
  cout<<"Der1 Exe "<<i<<endl;
  }
 };
class Derived2 : public Base
{    
 public: 
 void exec(int i)
 {
   cout<<"Der2 Exe "<<i<<endl;
 }
};
int main()
{   
  Base *client = NULL;  
  Derived1 lder1;
  Derived2 lder2;
  client= &lder2;
  Base::check(client);
  client->exec(0);
  client= &lder1;
  Base::check(client);
  client->exec(0);
 return 0;
}