背景:
PIMPL(指向实现的指针)是一种实现隐藏技术,其中一个公共类包装了一个在公共类所属的库之外看不到的结构或类。
这样可以隐藏用户库的内部实现细节和数据。
在实现此惯用法时,为什么要将公共方法放在 pimpl 类上而不是公共类上,因为公共类的方法实现会编译到库中,用户只有头文件?
为了说明,这段代码将 Purr()
实现放在 impl 类上并将其包装。
为什么不直接在公共类上实现 Purr ?
// header file:
class Cat {
private:
class CatImpl; // Not defined here
CatImpl *cat_; // Handle
public:
Cat(); // Constructor
~Cat(); // Destructor
// Other operations...
Purr();
};
// CPP file:
#include "cat.h"
class Cat::CatImpl {
Purr();
... // The actual implementation can be anything
};
Cat::Cat() {
cat_ = new CatImpl;
}
Cat::~Cat() {
delete cat_;
}
Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
printf("purrrrrr");
}