【发布时间】: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