syn*_*tik 4 c++ header-files static-libraries hide
我正在用C++创建一个静态库来定义一个其他人可以在代码中使用的类.但是,该类的成员是从其他人获取的头文件中定义的类型,我不想分发此人的头文件的内容.
这是当前的公共接口(interface.h):
class B {
TypeToHide t;
// other stuff ...
};
class A {
double foo();
B b;
};
Run Code Online (Sandbox Code Playgroud)
这里是将编译成静态库(code.cpp)的代码:
double A::foo() {
// ...
}
Run Code Online (Sandbox Code Playgroud)
这里是我需要从公共视图中隐藏的文件(HideMe.h):
struct TypeToHide {
// stuff to hide
};
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能隐藏HideMe.h的内容?理想情况下,我可以将整个结构从HideMe.h粘贴到code.cpp中.
你可以使用PIMPL习语(Chesshire Cat,Opaque Pointer,无论你想叫什么).
由于代码现在,你无法隐藏定义TypeToHide.替代方案是这样的:
//publicHeader.h
class BImpl; //forward declaration of BImpl - definition not required
class B {
BImpl* pImpl; //ergo the name
//wrappers for BImpl methods
};
//privateHeader.h
class BImpl
{
TypeToHide t; //safe here, header is private
//all your actual logic is here
};
Run Code Online (Sandbox Code Playgroud)