【发布时间】:2020-05-15 05:11:56
【问题描述】:
假设我正在开发一个日志记录功能。在logging.h 里面我声明了稍后应用程序使用的函数。
// logging.h
#include <string>
namespace logging {
void LogThis(const std::string& text);
}; // namespace logging
它的定义明显在logging.cpp里面:
// logging.cpp
void logging::LogThis(const std::string& text) {
std::cout << "Log: " << text << '\n';
}
现在让我们假设我的LogThis 函数的工作被拆分为一些较小的辅助函数。它们不是日志界面的一部分。我们以Prettify函数为例。
// logging.cpp
void logging::LogThis(const std::string& text) {
Prettify(text);
std::cout << "Log: " << text << '\n';
}
我的问题是:Prettify的函数声明应该放在哪里?我不应该将它包含在logging.h头文件中,因为那样它可以被其他编译单元调用它不是界面的一部分。所以把它放在logging.cpp 里面而不是这样?
// logging.cpp
namespace logging {
void Prettify(std::string& ugly_text);
void LogThis(const std::string& text) {
Prettify(text);
std::cout << "Log: " << text << '\n';
}
void Prettify(std::string& ugly_text) {
// making it pretty...
}
}
我正在寻找一些最佳实践/经验法则/对此的意见 :) 提前致谢!
【问题讨论】:
-
其他翻译单位想用吗?
-
不,Prettify 仅由该日志翻译单元使用。
-
把它放在 logging.cpp 中的匿名命名空间中
-
@JesperJuhl 放入匿名命名空间而不是
logging命名空间有什么好处? -
旁注:如果将
Prettify的定义放在LogThis的定义之上,则无需单独声明。
标签: c++ function coding-style encapsulation