7

他の人がコードで使用できるクラスを定義するために、C++ で静的ライブラリを作成しています。しかし、クラスのメンバーは、他の人から取得したヘッダー ファイルで定義された型であり、この人のヘッダー ファイルの内容を配布したくありません。

現在のパブリック インターフェイス (interface.h) は次のとおりです。

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

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

そして、スタティック ライブラリ (code.cpp) にコンパイルされるコードは次のとおりです。

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

そして、これが公開ビューから非表示にする必要があるコンテンツのファイルです (HideMe.h):

struct TypeToHide {
    // stuff to hide
};

HideMe.h の内容を非表示にするにはどうすればよいですか? 理想的には、HideMe.h の構造体全体を code.cpp に貼り付けるだけで済みます。

4

2 に答える 2

10

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

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
};
于 2012-12-16T16:37:54.257 に答える
3

Pimpl よりも単純で、ポインターTypeToHideとその前方宣言を使用できます。

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

ユーザーのコードの t の内部構造に関する知識が必要ない限り、それを公開する必要はなく、ライブラリ内で安全に保たれます。
ライブラリ内のコードは何が何であるかを知る必要がありますTypeToHideが、それは問題ではありません。

于 2012-12-16T17:16:39.490 に答える