隐藏第三方C ++头文件的内容 [英] Hide contents of third-party C++ header file

查看:127
本文介绍了隐藏第三方C ++头文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中创建一个静态库来定义一个类,别人可以在他们的代码中使用。但是,类的成员是在从其他人获得的头文件中定义的类型,并且我不想分发此人的头文件的内容。

I'm creating a static library in C++ to define a class that others can use in their code. However, a member of the class is of a type defined in a header file obtained from someone else, and I don't want to distribute the contents of this person's header file.

下面是当前的公共接口(interface.h):

Here is the current public interface (interface.h):

class B {
    TypeToHide t;
    // other stuff ...  
};

class A {
    double foo();
    B b;
};

这里是将编译成静态库(code.cpp)的代码:

And here is the code that will be compiled into a static library (code.cpp):

double A::foo() {
    // ...
}

这里是我需要隐藏的公开视图(HideMe.h)的文件:

And here is the file whose contents I need to hide from public view (HideMe.h):

struct TypeToHide {
    // stuff to hide
};

我可以隐藏HideMe.h的内容吗?理想情况下,我可以将整个结构从HideMe.h转换为code.cpp。

What can I do hide the contents of HideMe.h? Ideally, I could just stick the entire struct from HideMe.h into code.cpp.

推荐答案

可以使用PIMPL idiom

You can use the PIMPL idiom (Chesshire Cat, Opaque Pointer, whatever you want to call it).

代码现在,你不能隐藏 TypeToHide的定义。替代方法是:

As the code is now, you can't hide the definition of TypeToHide. The alternative is this:

//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
};

这篇关于隐藏第三方C ++头文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆