避免在类头文件中声明私有函数 (C++)
(在 C++ 中)我有一个类,其结构在头文件中声明。该头文件包含在许多源文件中,因此当我编辑它时,我需要重新编译许多文件。
该类具有一组仅在一个源文件中调用的私有函数。目前它们在头文件的类结构中声明。当我添加这种类型的新函数或编辑参数时,它会导致重新编译大量文件。我想在其他地方声明这些函数,这样只有定义和调用它们的文件才会被重新编译(以节省时间)。不过,他们仍然需要能够访问内部类变量。
我怎样才能实现这个目标?
(In C++) I have a class whose structure is declared in a header file. That header file is included in lots of source files, such that when I edit it I need to recompile lots of files.
The class has a set of private functions which are only called in one source file. Currently they are declared in the class structure in the header file. When I add a new function of this type, or edit the arguments, it therefore causes recompilation of lots of files. I would like to declare the functions somewhere else, such that only the file that defines and calls them is recompiled (to save time). They still need to be able to access the internal class variables, though.
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 pImpl 惯用语 - 您的可见类保留指向真实的指针类并将调用转发给公共成员函数。
编辑:响应评论
将类的实际实现保留在
FooImpl
中 -Foo
应该具有FooImpl 的 public 成员的副本
并简单地将呼叫转发给这些。所有用户将仅包含“Foo.h” - 您可以更改FooImpl
的所有私有详细信息,而Foo
的用户不会看到任何更改。Use the pImpl idiom - Your visible class keeps a pointer to the real class and forwards calls to public member functions.
EDIT: In response to comments
Keep the actual implementation of your class in
FooImpl
-Foo
should have copies of the public members ofFooImpl
and simply forward calls to these. All users will include only "Foo.h" - you can change all the private details ofFooImpl
without the users ofFoo
seeing any changes.无法在主类声明之外声明类的成员函数。因此,如果您想在相关类的外部声明可以访问该类特定实例的成员变量的函数,那么除了将该实例传递给该函数之外,我别无选择。此外,如果您希望函数能够访问私有变量和受保护变量,您需要将它们放入一个新类中,并使原始类成为该类的友元。例如
header.h:
impl.cpp:
There is no way to declare member functions of a class outside the main class declaration. So, if you want to declare, outside of the class in question, functions that can access member variables of a particular instance of the class, then I see no alternative but to pass that instance to the function. Furthermore, if you want the functions to be able to access the private and protected variables you will need to put them in a new class and make the original class a friend of that. E.g.
header.h:
impl.cpp:
您是否在寻找编译器防火墙(又名 PIMPL)?
Are you looking for Compiler Firewall, a.k.a. PIMPL?
创建一个仅包含公共函数的抽象基类,并在标头中引用它。创建您的真实类作为其他地方的实现。只有需要创建类的源文件才需要查看实现类头。
Create an abstract base class which contains only the public functions and reference this in your headers. Create your real class as an implementation somewhere else. Only source files which need to create your class need to see the implementation class header.