所以在我当前的项目中,我有 main.cpp、fruit.h 和fruit.cpp。
在main.cpp中,当前看起来像这样:
#include "fruit.h"
#include <Mouth.h>
int main() {
Fruit orange;
orange.wash(); //wash is a method of the Fruit class
Mouth mouth = NULL; //Mouth is a library I am using
if(mouth_init() != 0) {
return 1;
}
mouth = create_new_mouth();
if (mouth == NULL) {
return 1;
}
mouth_eat(orange);
clean_up_mouth();
mouth = NULL;
}
显然这是一个过于简化的示例,因为我实际的库初始化和退出函数更加复杂。但我正在考虑从 main 中取出初始化和清理代码,并创建辅助函数。现在我可以将这些辅助函数放入 main.cpp 中,但我正在考虑创建一个名为mouth.cpp 的新 C++ 文件,并将这些函数放入其中。但由于mouth.cpp不会有类,并且只会包含我的辅助函数,这是合法的,甚至是好的做法吗?如果允许,我是否应该创建一个也包含函数声明的mouth.h 文件?
最佳答案
对于 C++ 来说,头文件/cpp 文件中只包含函数是完全可以的。但是,在我看来,使用一个简单的类进行库初始化和反初始化会更优雅。
struct MouthLibHolder
{
MouthLibHolder(const MouthLibHolder&) = delete;
MouthLibHolder& operator=(const MouthLibHolder&) = delete;
MouthLibHolder()
{
if (!mouth_init())
throw std::runtime_error("Failed to init Mouth library");
}
~MouthLibHolder()
{
clean_up_mouth();
}
};
然后您可以在主函数中使用此代码,例如:
main()
{
try {
MouthLibHolder mouthLib;
...
}
...
}
持有者可以在单独的 h/cpp 文件中实现。
关于c++ - 将辅助函数分离到单独的 C++ 头文件/源文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34536928/