当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Including headers just for private data in a .h file

问题描述:

I have a class defined in class.cpp and class.h. The class uses some structures/classes/types/whatever defined in stuff.h (and of course, stuff.cpp) for private members and methods. My main program is in main.cpp, which #includes class.h, but doesn't care about anything in stuff.h. If it makes a difference, class.cp is supposed to be loaded dynamically (.dll/.so).

I would ideally like to have the stuff.h only included in class.cpp and stuff.cpp linked only to this file, as they would just cause name-space pollution in main.cpp and extra bloat by being linked to the final program.

The problem is that I have to include stuff.h in class.h, since it's definitions are used in the private: part of my class, which is all in class.h. And since main.cpp brings in class.h, it also gets stuff.h!

I hope this was clear. In C# this can be solved by partial classes. How would I do this in C++?

网友答案:

You do that in C++ by using pImpl aka Opaque Pointers where the class you expose only have one attribute which is a partially defined struct (sometimes people uses void* instead, but to same efefct).

The partially defined struct, then is fully defined inside your stuff.cpp and everything works as you expect -- the only snag is that you need to make sure that you constructor and destructor new/delete the internal implementation, and you need to make special provisions in your copy constructor and and your assignment operator operator= -- most people opt for just make the copy constrctor and assignment operators private, so that the compiler will object if they are used.

网友答案:

Looks like you need Pimpl Idiom here. The main idea of Pimpl is that you forward declare class with implementation instead of including it's definition. This allows you to remove dependencies on implementation in header files, which usually results in compilation speed up, especially on large projects.

分享给朋友:
您可能感兴趣的文章:
随机阅读: