背景资料:
PIMPL Idiom (指向 IPLementation的指针)是一种实现隐藏技术,其中公共类包装了在公共类所属的库之外无法看到的结构或类。
这对库的用户隐藏了内部实现细节和数据。
在实现这个习惯用法时,为什么要将公共方法放在 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");
}