c++ - 继承期间受保护成员的 pimpl
问题描述
我在派生类使用的`基类 hpp 文件中声明了大量受保护的成员函数。我的想法是从头文件中删除它们以减少编译依赖。我也想过对受保护的成员使用 pimpl 方法。
我在Base class cpp 文件中定义了一个Impl类,并将所有受保护的函数移动到Impl类中。此外,我在基类头文件中将Impl类前向声明为受保护的成员。
protected:
class Impl;
Impl* impl_;
但这样做时,当我使用派生类中的 impl_ 调用受保护函数时,派生类编译中发生以下错误:
error: invalid use of incomplete type ‘class Base::Impl’
if (false == impl_->EncodeMMMsgHeader(mm_msg_header_)) {
error: forward declaration of ‘class Base::Impl’
我认为发生错误是因为在编译器需要有关类的上下文信息的任何情况下都不能使用前向声明,编译器也没有任何用处,只告诉它关于类的一点点。
有什么办法可以克服上述问题吗?如果没有,那么任何人都可以建议我更好的方法来实现我的目标。
解决方案
你可以添加一个层来减少依赖:
从
#include "lot_of_dependencies"
#include <memory>
class MyClass
{
public:
~MyClass();
/*...*/
protected:
/* Protected stuff */
private:
struct Pimpl;
std::unique_ptr<Pimpl> impl;
};
添加
MyClassProtectedStuff.h
#include "lot_of_dependencies"
class MyClassProtectedStuff
{
public:
/* Protected stuff of MyClass */
private:
// MyClass* owner; // Possibly back pointer
};
接着
我的类.h
#include <memory>
class MyClassProtectedStuff;
class MyClass
{
public:
~MyClass();
/*...*/
protected:
const MyClassProtectedStuff& GetProtected() const;
MyClassProtectedStuff& GetProtected();
private:
struct Pimpl;
std::unique_ptr<Pimpl> impl;
std::unique_ptr<MyClassProtectedStuff> protectedData; // Might be in Piml.
};
然后派生类应该包含两个标题,而常规类只包含 MyClass.h
推荐阅读
- fortran - Fortran 90 和 95 的语法有什么不同吗?
- node.js - 从 Nodejs 代码生成 Microsoft Graph API 令牌
- javascript - 试图将我的 node.js 应用程序上传到 heroku,它说 Web 进程在启动后 60 秒内未能绑定到 $PORT,进程以状态 137 退出
- html - 解析 HTML 并将 PDF 写入磁盘(python)
- powershell - 无法从阈值列表中获取任何工作流
- javascript - 如何使用 Jasmine 在任何 Angular 应用程序中测试 RXJS 实用程序,如管道、跳过、点击、重试等
- python - 在 DialogFlow 中,是否可以从本地文件而不是 URL 输出图像?
- mongodb - 连接数字海洋上的mongodb服务器
- javascript - 带有数字填充的 CSS 计数器
- javascript - 异步每个系列都没有显示正确的结果,显示数组的一个元素而不是所有元素