相关疑难解决方法(0)

为什么要使用"PIMPL"成语?

背景资料:

所述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");
}
Run Code Online (Sandbox Code Playgroud)

c++ oop information-hiding pimpl-idiom

128
推荐指数
5
解决办法
10万
查看次数

标签 统计

c++ ×1

information-hiding ×1

oop ×1

pimpl-idiom ×1