簡體   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