简体   繁体   English

是否应从头文件声明中排除辅助函数? (C ++)

[英]Should helper functions be excluded from header file declarations? (C++)

Should helper functions which are only used within the implementation file be excluded from header file declarations? 是否应该从头文件声明中排除仅在实现文件中使用的辅助函数?

By helper function I mean a convenience function that is closely associated with a class, but doesn't represent an operation on the class, does not need access to member variables, and as such is not a method. 通过辅助函数,我指的是与类紧密关联的便捷函数,但不表示对类的操作,不需要访问成员变量,因此不是方法。

On one hand, including them in the header file makes the header file a comprehensive reference for the corresponding c++ implementation. 一方面,将它们包含在头文件中使得头文件成为相应c ++实现的综合参考。 On the other hand, it introduces one more piece of code to maintain for consistency. 另一方面,它引入了一段代码来保持一致性。 More importantly, including helper functions encourages minor violations of a layer of abstraction, in the sense that the function isn't meant to be run in other contexts, although not in a severe way since there's not a risk of corrupting class state so long as the helper function itself is not breaking encapsulation of classes it works with. 更重要的是,包括辅助函数会鼓励轻微违反抽象层,因为函数并不意味着在其他环境中运行,尽管不是以严格的方式运行,因为不存在破坏类状态的风险,只要辅助函数本身并没有破坏它所使用的类的封装。

On one hand, including them in the header file makes the header file a comprehensive reference for the corresponding c++ implementation. 一方面,将它们包含在头文件中使得头文件成为相应c ++实现的综合参考。

That's not the purpose of a header file. 这不是头文件的目的。 A header file is supposed to be a reference for the interface , not the implementation . 头文件应该是接口的引用,而不是实现 Some implementation details will sometimes leak through, but this should be avoided wherever possible. 有些实现细节有时会泄漏,但应尽可能避免这种情况。

So to answer your headline question: yes. 所以回答你的标题问题:是的。

If they're used in one part of the implementation only they should be excluded from the main header files. 如果它们在实现的一部分中使用,则只应从主头文件中排除它们。 However if you wish to test those function you will want to add references to them to a separate headerfile. 但是,如果您希望测试这些函数,则需要将对它们的引用添加到单独的头文件中。

If they're used in multiple parts of the implementation they'll belong in their own internal header file so that they can be shared. 如果它们在实现的多个部分中使用,则它们将属于它们自己的内部头文件,以便可以共享它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM