另一个第三种解决方案?
一个细微的区别是枚举必须在标题中定义,并且对所有人可见。当您避免依赖时,这很痛苦。例如,在 PImpl 中,添加枚举会适得其反:
// MyPImpl.hpp
class MyImpl ;
class MyPimpl
{
public :
enum { Life = 42 } ;
private :
MyImpl * myImpl ;
}
另一个第三种解决方案是问题中提出的“const static”替代方案的变体:在标头中声明变量,但在源代码中定义它:
// MyPImpl.hpp
class MyImpl ;
class MyPimpl
{
public :
static const int Life ;
private :
MyImpl * myImpl ;
}
.
// MyPImpl.cpp
const int MyPImpl::Life = 42 ;
请注意,MyPImpl::Life 的值对 MyPImpl 的用户(包括 MyPImpl.hpp)是隐藏的。
这将使 MyPimpl 作者能够根据需要更改“Life”的值,而无需 MyPImpl 用户重新编译,这是 PImpl 的总体目标。