Hiding private data members? (C++)

后端 未结 5 2025
北海茫月
北海茫月 2020-12-13 00:21

Is there a way to hide private data members of a C++ class away from its users, in the cpp file? I think of the private members as part of the implementation and it seems a

相关标签:
5条回答
  • 2020-12-13 00:26

    The "pimpl" idiom is how this is generally handled.

    See

    • http://www.gotw.ca/gotw/024.htm
    • http://www.gotw.ca/gotw/028.htm
    • http://herbsutter.com/gotw/_100/ (updated for C++11)
    0 讨论(0)
  • 2020-12-13 00:31

    you want to use something like the PIMPL idiom

    http://en.wikipedia.org/wiki/Opaque_pointer

    0 讨论(0)
  • 2020-12-13 00:40

    See Pimpl Idiom

    0 讨论(0)
  • 2020-12-13 00:47

    Going commercial? ;)

    You can create header files, in which you only declare the public and protected API.

    The user is only presented with these, which they can include. They link their code with a library, which you built using the complete API and the definitions.

    For inlined functions: make sure they are used in non-inlined code, then there will be a definition available in the library (I'm not sure it will be inlined in the user implemenation, however).

    For templated code there is no real way around. One half-hearted solution is to make code, which uses the templated code with different object types. The user will be limited to these, because they are the only definitions available in your library.

    0 讨论(0)
  • 2020-12-13 00:53

    The classic way to do this is with a proxy pointer to an internal class which implements the functionality. There's no way to do partial class definitions in C++ that I know of.

    0 讨论(0)
提交回复
热议问题