我正在编写一个依赖于另一个库(称为 ParentLib)的共享库(称为 MyLib)。 ParentLib 有一些虚函数,我在 MyLib 中实现了这些虚函数以及其他几个独立的实现。
// MyLib.h
#include <parentlib_library.h>
class Foo : public ClassinParent
{
public:
void DefinitionofParentLibFunction();
private:
// ...
};
我能够毫无问题地编译和生成 MyLib,但是当应用程序使用 MyLib 时,我需要包含 ParentLib_library.h 来编译代码。 我的要求之一是 ParentLib 应该对应用程序完全隐藏。我不确定实现这一目标的下一步。 有什么想法吗?
最佳答案
如果您的声明用于回调或来自 3dparty lib 的接口(interface)实现 - 那么没办法。在所有其他情况下,我通常采用以下 3 种方法。
1) 使用聚合。将 ClassInParent 声明为 forward 并作为 Foo 的成员使用:
class ClassInParent;//forward declare
class Foo
{
ClassInParent* _inst; //use either pointer of reference to external
public:
void method_of_ClassInParent() //make facade for parent methods if needed
}
2) 将您的类分成接口(interface)(不依赖于 ClassInParent)和实现(不通过 #include
公开)
你的 Foo.h:
class Foo
{
public:
virtual void do_smth() = 0;
};
你的 Foo.cpp:
#include <parentlib_library.h>
class FooImpl : public Foo, public ClassInParent
{
void do_smth()
{//implementation
3) 使用模板。而不是显式继承使用模板:
template <class T>
class Foo : public T
{
稍后在您的代码中 Foo<ClassInParent>
关于c++ - 隐藏包含父库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19375395/