如何找出正在处理的派生类
How to find out which derived class is processing
我有一个 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;
}
相关文章:
- 警告处理为错误这里有什么问题
- 将 URL/href 从网络服务器重新派生到ESP8266(以处理它)
- 为什么隐式转换在异常处理中从派生到基?
- 设置一系列基/派生类来处理天气数据
- 编译器如何处理基类破坏者在派生的破坏者中调用
- 统一处理具有协变类型的函数指针(如何使用派生类型调用回调?
- 如何使派生类的流式处理运算符也输出基类
- 我如何处理成员的所有派生动态内存
- SWIG:在派生类中处理基类重载方法
- 如何找出正在处理的派生类
- C++异常处理如何处理异常派生类
- 从std::tuple派生时出现混乱,无法处理std::get
- 使用基类而不是基指针来处理派生类
- 在派生类中使用提取运算符(>>)的方法以及在C++中处理静态数据成员的方法
- 使用 static_cast 处理混合(基础和派生)对象的向量是否存在性能风险?(又名 "it this a dumb idea?" )
- 在c++中使用映射器处理派生类的创建
- 在派生类中处理派生对象集合的最佳方法是什么?
- 处理派生类的细节而不向下转换
- 帮助处理类和派生类
- 事件处理:当接收者期望派生类时,从基类发送事件