实现一个类的时候,有个时候需要用到一些公共的函数,这些函数不依赖类的成员变量,这些函数应该放在同文件里面作为全局函数还是放到头文件中作为私有成员函数?
例如:
对于一个配置文件读取类,需要一个函数将读取的颜色字符串"#aabbcc"转换成结构体Color{ float r,g,b;};
私有成员版本:
// loader.h
class Loader{
public:
void foo();
private:
Color StringToColor(std::string s){...} // private version
};
// loader.cpp
void Loader::foo()
{
...
Color c = StringToColor(s);
}
同文件的全局函数版本:
// loader.cpp
Color StringToColor(std::string s){...} // global version
void Loader::foo()
{
...
Color c = StringToColor(s);
}
如果用私有成员版本,可能会导致头文件膨胀,特别是这些函数要用到某些库函数的时候,需要将库文件包含到头文件中。
如果用全局函数版本,好像不怎么OOP。一般来说,哪种实现更好呢?
PHP中文网2017-04-17 15:20:29
There is no need to OOP
just for the sake of OOP
, C++
is not just a OOP
paradigm, unless your company has regulations that must be followed
If you are sure that StringToColor
is just an auxiliary function of Loader
and does not depend on the internal variables of the class, you can define it in the anonymous namespace
// loader.cpp
namespace
{
Color StringToColor(std::string s){...}
}
void Loader::foo()
{ ...
Color c = StringToColor(s);
}
In this way, StringToColor
will only be visible inside Loader.cpp
and will not be exposed to the whole world
If you are not familiar with namespaces, you can also use the C
concept of static
and define StringToColor
as static, but this way of writing is not recommended:
// loader.cpp
static Color StringToColor(std::string s){...}
void Loader::foo()
{ ...
Color c = StringToColor(s);
}
can also play a role that is only visible inside loader.cpp