首页 > 解决方案 > 继承期间受保护成员的 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’

我认为发生错误是因为在编译器需要有关类的上下文信息的任何情况下都不能使用前向声明,编译器也没有任何用处,只告诉它关于类的一点点。

有什么办法可以克服上述问题吗?如果没有,那么任何人都可以建议我更好的方法来实现我的目标。

标签: c++oopinheritanceprotectedpimpl-idiom

解决方案


你可以添加一个层来减少依赖:

#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


推荐阅读