gpt4 book ai didi

c++ - 将辅助函数分离到单独的 C++ 头文件/源文件中

转载 作者:搜寻专家 更新时间:2023-10-31 02:18:25 25 4
gpt4 key购买 nike

所以在我当前的项目中,我有 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 文件?

最佳答案

只有头文件/cpp 文件中的函数对于 C++ 来说是完全可以的。但是,IMO,使用一个简单的类来进行库初始化和取消初始化会更优雅。

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;
...
}
...
}

holder 可能在单独的 h/cpp 文件中实现。

关于c++ - 将辅助函数分离到单独的 C++ 头文件/源文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34536928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com