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

时间:2016-06-28 14:05:59

标签: c++ interface hide implementation details

我对更高级的C ++功能相对较新......所以请记住这一点;)

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

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

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

所以如果我有一个看起来像这样的Interface.h头文件:

class Interface
{
  public:
    Interface(){};
    virtual ~Interface(){};
    virtual void InterfaceMethod() = 0;
}

然后,具体的Implementation.h头文件如下所示:

class Implementation : public Interface
{
  public:
    Implementation(){};
    virtual ~Implementation(){};
    void InterfaceMethod();
    void ImplementationSpecificMethod();
}

最后,在主要的情况下,我有:

int main()
{
  Interface *pInterface = new Implementation();
  // some code
  delete pInterface;
  return 0;
}

我怎么能做这样的事情,而不透露来自" main"的Implementation.h的详细信息?难道没有办法告诉"主要" ......嘿,"实施"只是一种"界面&#34 ;;并将其他所有内容保存在一个单独的库中?

我知道必须是一个重复的问题...但我无法找到明确的答案。

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

您可以使用工厂。

部首:

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

Abstract* create();

来源:

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

Abstract* create()
{
    return new Concrete();
}

答案 1 :(得分:0)

您可以通过使用类似PIMPL的内容隐藏.cpp文件中的实现细节,从头文件中的简单视图隐藏您的Implementation类的一些内部细节(私有)。

有关pimpl习语的更多讨论,请参阅Is the pImpl idiom really used in practice?

答案 2 :(得分:0)

虽然工厂解决方案更适合OP问题,但我认为PIMPL版本也能解决同样的问题。它有点做作,但避免使用虚拟界面:

// Header file:
class Interface
{
    struct Implementation;
    std::unique_ptr< Implementation > m_impl;

  public:
    Interface();
    ~Interface();
    void InterfaceMethod();
};

// Implementation file:
class Interface::Implementation
{
  public:
    void ImplementationSpecificMethod()
    {
        std::cout << "Bla" << std::endl;
    }
};

Interface::Interface()
    : m_impl( std::make_unique< Interface::Implementation >( ) )
{ }

Interface::~Interface() = default;

void Interface::InterfaceMethod( )
{
    m_impl->ImplementationSpecificMethod();
}

// Main file:
int main()
{
    Interface i;
    i.InterfaceMethod(); // prints Bla
}