繁体   English   中英

在运行时定义的C ++纯虚拟方法

[英]C++ pure virtual method defined at run-time

不知道这个名字是否很有说服力,可是到了。

我正在连接一个API,该API需要继承基类并定义许多纯虚拟方法。

为了实现良好的编程习惯,我希望在不同的(子)类中定义这些方法。

当前,我使用facade / wrapper(两者都有)类,该类继承了基类,实例化了子类,并调用了这些实例化类的必要方法:

#include <cstdio>

class Base
{
  public:
    virtual void reqImplementation( void ) = 0;
};

class APIImplementation
{
  private:

    Base * ptr_;

  public:
    APIImplementation( Base * ptr ) :
      ptr_( ptr )
    {
      ptr_->reqImplementation();
    }
};

class MyImplementation
{
  private:
    APIImplementation * api_;
  public:
    void reqImplementation( void )
    {
      printf("Hello World!\n");
    }

    MyImplementation( APIImplementation * api ) : api_( api ) {}
};

class MyFacade : public Base
{
  private:
    MyImplementation * my_impl_;
    APIImplementation * api_;

    void reqImplementation( void )
    {
      my_impl_->reqImplementation();
    }

  public:
    MyFacade( void )
    {
      api_ = new APIImplementation( this );
      my_impl_ = new MyImplementation( api_ );
    }
};

int main( void )
{
  MyFacade my_facade;
  return 0;
}

有什么方法可以在此Facade / wrapper中实例化的子类中实现纯虚函数? 或者,对于这样的事情,什么是好的做法? 我想要类似的东西(我知道它目前显然不起作用):

#include <cstdio>

class Base
{
  public:
    virtual void reqImplementation( void ) = 0;
};

class APIImplementation
{
  private:

    Base * ptr_;

  public:
    APIImplementation( Base * ptr ) :
      ptr_( ptr )
    {
      ptr_->reqImplementation();
    }
};

class MyImplementation : public Base
{
  private:
    APIImplementation * api_;
  public:
    void reqImplementation( void )
    {
      printf("Hello World!\n");
    }

    MyImplementation( APIImplementation * api ) : api_( api ) {}
};

class MyFacade : public Base
{
  private:
    MyImplementation * my_impl_;
    APIImplementation * api_;

  public:
    MyFacade( void )
    {
      api_ = new APIImplementation( this );
      my_impl_ = new MyImplementation( api_ );
    }
};

int main( void )
{
  MyFacade my_facade;
  return 0;
}

请注意,API源代码是开放的,因此我可以将这些纯虚拟方法更改为其他任何方法,但是代码相当详尽,因此我宁愿进行较小的更改,也不愿进行重大更改。

如果我理解正确,则需要虚拟继承。 这是一个例子

#include <iostream>
using namespace std;

// base class with lots of methods (two, actually)
struct Base {
    virtual void f() = 0;
    virtual void g() = 0;
};

// here's a class with implementation of f
struct ImplementationPart1 : public virtual Base {
    virtual void f() {
        cout << 4;
    }
};

// here's a class with implementation of g
struct ImplementationPart2 : public virtual Base {
    virtual void g() {
        cout << 2;
    }
};

// here's a class with all the implementations
struct Implementation : public ImplementationPart1, public ImplementationPart2 {};

int main() {
    // Implementation inherits from Base, yes
    Base *x = new Implementation();
    // everything works, as expected
    x->f();
    x->g();
}

现场示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM