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

时间:2014-01-15 03:24:39

标签: c++

我有一个BaseInterface类,虚拟void execute()由派生类实现:

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

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

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

执行某个派生类的void有一个bug。但是有很多派生类。很难逐一检查每一个。我很难找到这个错误。

C ++中是否有一个方法来查找via base类,哪个派生类正在处理它?<​​/ p>

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

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

2 个答案:

答案 0 :(得分:1)

您正在寻找typeid

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(); }
};

答案 1 :(得分:0)

如何调用execute ....可以在基类中引入静态方法,该方法将Baseclass指针作为参数并在执行之前调用此方法并使用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;
}
相关问题