开发者

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 anythi开发者_开发问答ng 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜