【问题标题】:Hiding specific implementation of C++ interface隐藏C++接口的具体实现
【发布时间】:2016-10-30 21:55:03
【问题描述】:

我对更高级的 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();
}

最后,在 main 下,我有:

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

如何在不从“main”中透露 Implementation.h 的详细信息的情况下做这样的事情?有没有办法告诉“main”...嘿,“Implementation”只是一种“Interface”;并将其他所有内容保存在单独的库中?

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

感谢您的帮助!

【问题讨论】:

  • Factory function,类似于Interface* MakeInterface() { return new Implementation; }。只有函数声明需要在标题中发布,并且它本身并没有提及Implementation
  • @Igor Tandetnik 谢谢伊戈尔。如果您将其作为答案,我会将其标记为已回答学分。
  • 不要delete的东西。寻找智能指针。
  • @SergeyA 嗯...这将是我下一个学习阶段的一部分... ;)

标签: c++ interface hide implementation


【解决方案1】:

你可以使用工厂。

标题:

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

Abstract* create();

来源:

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

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

【讨论】:

    【解决方案2】:

    您可以使用 PIMPL 之类的东西隐藏 .cpp 文件中的实现细节,从而在头文件中轻松查看实现类的一些内部细节(私有)。

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

    【讨论】:

    • 这似乎没有回答这个问题。 OP 没有询问如何隐藏派生类的实现细节。相反,他们询问如何避免从 main 函数显式实例化派生类型(即,main 函数只知道接口类型而不知道派生类型)。
    【解决方案3】:

    虽然工厂解决方案更适合 OP 问题,但我认为 PIMPL 版本也可以解决相同的问题。它有点做作但避免了虚拟接口:

    头文件:

    class Interface
    {
        struct Implementation;
        std::unique_ptr< Implementation > m_impl;
    
      public:
        Interface();
        ~Interface();
        void InterfaceMethod();
    };
    

    实现文件:

    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();
    }
    

    主文件:

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

    在线查看repl.it

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多