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

标签 c++ oop abstraction

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

相关文章:

通过 DispatchProxy 进行 C# 日志记录

c++ - 对象作为 CMap 中的键

c++ - gflags 链接器错误 : undefined reference

c++ - 在混合 C/C++ 程序中协调 malloc 和 new 的 "correct"方法是什么?

java - Java相关的fold()函数如何实现函数签名?

python - 在类内访问 `__attr` 时,名称修改如何工作?

PHP:我应该传入并返回这些变量吗?

c++ - 有什么理由不使用 c++0x 进行 iOS 开发吗?

.net - 将文本应用于第三方控件时的编程问题

domain-driven-design - 工作单元模式中的回滚方法的意图是什么?