包括仅用于.h文件中的私有数据的头 [英] Including headers just for private data in a .h file
问题描述
我在 class.cpp
和 class.h
中定义了一个类。该类使用一些结构/类/类型/在 stuff.h
(当然, stuff.cpp
)私人成员和方法。我的主程序在 main.cpp
,其中 #include
s class.h
,但不关心
stuff.h
中的任何内容。如果它有区别, class.cp
应该动态加载(.dll / .so)。
我理想地希望有 stuff.h
仅包含在 class.cpp
和 stuff.cpp
仅链接到此文件,因为它们只会导致 main.cpp
中的命名空间污染,并通过链接到最终程序而额外膨胀。
问题是,我必须在 class.h
中包含 stuff.h
,因为它的定义 private:
是我的类的一部分,这全部在 class.h
中。由于 main.cpp
带来 class.h
,它也会得到 stuff.h
!
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 #include
s 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
!
我希望这一点很清楚。在C#中,这可以通过部分类来解决。
I hope this was clear. In C# this can be solved by partial classes. How would I do this in C++?
推荐答案
你可以在C ++中使用pImpl aka Opaque Pointers 其中你公开的类只有一个属性是一个部分定义的结构(有时人们使用void *而不是相同的efefct )。
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).
部分定义的struct,然后在 stuff.cpp
中完全定义, - 唯一的障碍是,你需要确保你的构造函数和析构函数新的/删除内部实现,你需要在你的复制构造函数和你的赋值运算符 operator =
- 大多数人选择只是使复制constrctor和赋值运算符私有,这样编译器将对象,如果他们被使用。
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.
这篇关于包括仅用于.h文件中的私有数据的头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!