C ++中具有多态性的静态方法 [英] static method with polymorphism in c++

查看:107
本文介绍了C ++中具有多态性的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用多态性的怪异问题. 我有一个实现静态方法的基类.由于各种原因,此方法必须是静态的.基类还具有一个纯虚方法run(),该方法由所有扩展类实现.我需要能够从静态类中调用run().

I have a weird issue using polymorphism. I have a base class that implements a static method. This method must be static for various reasons. The base class also has a pure virtual method run() that gets implemented by all the extended classes. I need to be able to call run() from the static class.

当然,问题在于静态类没有this指针.可以在void *参数中传递此方法.我一直试图想出一种聪明的方法来将run方法传递给它,但是到目前为止,仍然没有任何效果.也尝试将其传递给它.问题是我必须实例化它,这需要扩展类的知识.这破坏了多态性的全部目的.

The problem, of course, is that the static class doesn't have a this pointer. This method can be passed in a void * parameter. I have been trying to come up with a clever way to pass the run method into it, but nothing has worked so far. have also tried passing this into it. The problem with this is that I would then have to instantiate it, which requires knowledge of the extended class. This defeats the whole purpose of the polymorphism.

关于如何解决这个问题的任何想法?

Any ideas on how to go about this?

推荐答案

不要将其作为void *指针传递,而应将其作为指针(或引用)传递给基类:

Don't pass it as a void* pointer, pass it as a pointer (or reference) to the base class:

class BaseClass
{
public:
  static void something(BaseClass* self) { self->foo(); }
  virtual void foo() = 0;  
};

这篇关于C ++中具有多态性的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆