隐藏C++接口的具体实现

The*_*moX 5 c++ implementation interface hide

我对更高级的 C++ 功能还比较陌生......所以请记住这一点;)

我最近为某个类定义了一个接口,当然,仅包含纯虚函数。

然后,我在单独的文件中实现了该接口的特定版本。

问题是......我如何在用户端调用该接口的特定实现,而不透露该特定实现的内部结构?

因此,如果我有一个如下所示的 Interface.h 头文件:

class Interface
{
  public:
    Interface(){};
    virtual ~Interface(){};
    virtual void InterfaceMethod() = 0;
}
Run Code Online (Sandbox Code Playgroud)

然后,一个特定的Implementation.h头文件如下所示:

class Implementation : public Interface
{
  public:
    Implementation(){};
    virtual ~Implementation(){};
    void InterfaceMethod();
    void ImplementationSpecificMethod();
}
Run Code Online (Sandbox Code Playgroud)

最后,在 main 下,我有:

int main()
{
  Interface *pInterface = new Implementation();
  // some code
  delete pInterface;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做这样的事情,而不透露“main”中Implementation.h的细节?难道就没有办法告诉“main”吗……嘿,“实现”只是“接口”的一种;并将其他所有内容保存在单独的库中?

我知道这一定是一个重复的问题......但我找不到明确的答案。

谢谢您的帮助!

Iva*_*son 6

您可以使用工厂。

标题:

struct Abstract
{
    virtual void foo() = 0;
}

Abstract* create();
Run Code Online (Sandbox Code Playgroud)

来源:

struct Concrete : public Abstract
{
    void foo() { /* code here*/  }
}

Abstract* create()
{
    return new Concrete();
}
Run Code Online (Sandbox Code Playgroud)